I have a question about How to delete a space in my guessing game.
Here is my source code:
import random
print ("I’m thinking of an integer, you have three guesses.")
def tovi_is_awesome():
random_integer = random.randint (1, 10)
chances = 3
for i in [1,2,3]:
print ("Guess", i, ": ", end=" ")
guess = eval(input("Please enter an integer between 1 and 10: "))
if guess < random_integer:
print ("Your guess is too small.")
elif guess > random_integer:
print ("Your guess is too big.")
else:
print ("You got it!")
break
if guess != random_integer:
print ("Too bad. The number is: ", random_integer)
tovi_is_awesome ()
When I run it, I got this:
I’m thinking of an integer, you have three guesses.
Guess 1 : Please enter an integer between 1 and 10:
How can I delete that space after "Guess 1"?
Or are there any better ways to avoid that space?
Thank you!
This is my first question in SOF lol
print ("Guess", i, ": ", end=" ")
You could write it like;
print ("Guess {}: ".format(i), end=" ")
So you can avoid from that space. You could check this one for examples.
Here is a simple guess game, check it carefully please. It may improve your game. You dont' have to use eval().
random_integer = random.randint (1, 10)
chances = 3
gs=1
while 0<chances:
print ("Guess {}".format(gs))
guess = int(input("Please enter an integer between 1 and 10: "))
if guess<random_integer:
print ("Your guess is too small.")
chances -= 1 #lost 1 chance
gs += 1 #increase guess number
elif guess > random_integer:
print ("Your guess is too big.")
chances -= 1
gs +=1
else:
print ("You got it!")
break
It's really simple, just showing you some basic logic. You may consider in the future catching errors with try/except etc.
print ("Guess %d:" % (i) )
Writing this way will delete the space.
Related
Is there a way to fix the obtaining negative numbers in the code below?
import random
number = random.randrange(1, 100)
guess = int(input("I’m thinking of a number between 1 and 100 " + "Can you guess it? "))
number1 = number - guess
number2 = (number) - guess
if guess>number:
print ("You were " + str(number1)+ " away! ")
else:
if guess<number:
print ("You were " + str(number2)+ " away! ")
else:
if guess == number:
print ("You got it right ")
the whole code should be simplified to:
import random
number = random.randint(1, 100)
guess = int(input("Im thinking of a number between 1 and 100 Can you guess it? "))
if guess!=number:
print ("You were",abs(guess-number),"away! ")
else:
print ("You got it right ")
Or just:
print(["You were "+str(abs(guess-number))+" away! ","You got it right "][number==guess])
Whole code:
import random
number = random.randint(1, 100)
guess = int(input("Im thinking of a number between 1 and 100 Can you guess it? "))
print(("You were "+str(abs(guess-number))+" away! ","You got it right ")[number==guess])
abs() will return the absolute value of the difference.
abs(number - guess)
So, I have this program where you have to guess a number and I've coded it so that the program will tell you if the number you guessed was above or below the true number. My issue is that the program ends after it tells the user to guess higher or lower. I want the program to loop such that the program won't end until the number that I preset is guessed.This is my code:
number = 10
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
elif guess < number:
print ("The number is higher")
else:
print ("The number is lower")
while guess!= number:
print ("Try Again")
print ("Done")
I tried to use a while loop to loop the program until the number was correctly guessed, but the "Try Again" script was looped forever... Thanks for the help!
Your flow control was not properly designed, but you can fix by wrapping your code in the while loop, and applying break once guess == number. The other cases where guess!=number, the loop just keeps running:
number = 10
while True:
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
break
elif guess < number:
print ("The number is higher")
else:
print ("The number is lower")
print ("Done")
You can read more about while loops in python here
while loops don't work that way. It looks like you're expecting some kind of goto where it guesses what you would like it to repeat, but all it will repeat is the content of the block. When it gets to while guess != number:, which is true, it will print that phrase, then check whether guess is not equal to number, which will still be true because it hasn't changed, forever.
Put everything that needs to be repeated into the loop:
number = 10
guess = int(input("Type in an integer: "))
while guess != number:
if guess < number:
print ("The number is higher")
else:
print ("The number is lower")
guess = int(input("Type in an integer: "))
print ("Good Job!")
print ("Done")
Try the following:
number = 10
guess = 9
while guess!= number:
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
elif guess < number:
print ("The number is higher")
elif guess > number:
print ("The number is lower")
else:
print ("Try Again")
print ("Done")
I'm new to python and I'm trying to make the guess my number game with a limit of only 5 guesses, everything I've tried so far has failed. how can I do it?, I forgot to mention that I wanted the program to display a message when the player uses all their guesses.The code below only prints the "You guessed it" part after the 5 guesses whether they guess it or not.
import random
print ("welcome to the guess my number hardcore edition ")
print ("In this program you only get 5 guesses\n")
print ("good luck")
the_number = random.randint(1, 100)
user = int(input("What's the number?"))
count = 1
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5:
break
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
input ("\nPress enter to exit")
Your edit says you want to differentiate between whether the loop ended because the user guessed right, or because they ran out of guesses. This amounts to detecting whether you exited the while loop because its condition tested false (they guessed the number), or because you hit a break (which you do if they run out of guesses). You can do that using the else: clause on a loop, which triggers after the loop ends if and only if you didn't hit a break. You can print something only in the case you do break by putting the print logic right before the break, in the same conditional. That gives you this:
while user != the_number:
...
if count == 5:
print("You ran out of guesses")
break
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
However, this puts code for different things all over the place. It would be better to group the logic for "guessed right" with the logic for warmer/colder, rather than interleaving them with part of the logic for how many guesses. You can do this by swapping where you test for things - put the 'is it right' logic in the same if as the warmer/colder, and put the number of guesses logic in the loop condition (which is then better expressed as a for loop). So you have:
for count in range(5):
user = int(input("What's the number?"))
if user > the_number:
print("Lower")
elif user < the_number:
print("Higher")
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
break
else:
print("You ran out of guesses")
You have two options: you can either break out of the loop once the counter reaches a certain amount or use or a for loop. The first option is simplest given your code:
count = 0
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5: # change this number to change the number of guesses
break # exit this loop when the above condition is met
This is my first time visiting using stackoverflow--I'm new to programming and am taking a beginner's course for Python. Excited to get started!
Our second assignment asks us to create the well-known Guess the Number Game. For those of you who already know this game, I would love some help on an extra piece that's been added to it: we must list off each guess with their respective order. A sample output should look like this:
I'm thinking of an integer, you have three guesses.
Guess 1: Please enter an integer between 1 and 10: 4
Your guess is too small.
Guess 2: Please enter an integer between 1 and 10: 8
Your guess is too big.
Guess 3: Please enter an integer between 1 and 10: 7
Too bad. The number is: 5
I've got the coding down to where I have Guess 1 and Guess 3 appear, but I cannot make Guess 2 appear. I've been reworking and replacing every "while", "if", "elif", and "else" command to fix this, but can't seem to come up with a solution! Here is my code so far:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
guess = eval(input("Guess 1: Please enter an integer between 1 and 10: "))
while guess != number and attempts == 0:
if guess < number:
print("Your guess is too small.")
break
if guess > number:
print("Your guess is too big.")
break
elif guess == number:
print("You got it!")
attempts = attempts + 1
if number != guess and attempts == 1:
guess = eval(input("Guess 2: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
while guess == number:
print("You got it!")
attempts = attempts + 1
elif number != guess and attempts == 2:
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
while guess == number:
print("You got it!")
This code outputs Guess 1 and then quits. Can anyone help me figure out how to make Guess 2 and 3 appear?? All ideas are welcome--Thanks!
You can shorten you code quite a bit, just move the input in the loop and keep looping for either three attempts using range or the user guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
from random import randint
number = randint(0,10)
# loop three times to give at most three attempts
for attempt in range(3):
# cast to int, don't use eval
guess = int(input("Guess 1: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
else: # not higher or lower so must be the number
print("You got it!")
break
It would be better to use a while with a try/except to verify the user inputs a number, looping until the user has used 3 attempts or guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
while attempts < 3:
try:
guess =int(input("Guess 1: Please enter an integer between 1 and 10: "))
except ValueError:
print("That is not a number")
continue
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else: # if it is a number and not too high or low it must be correct
print("You got it!")
break # break the loop
You cannot just use an if/else if you actually want to give the user feedback on whether their guess was too low or too high.
Also as commented don't use eval. Some good reason why are outlined here
All your while guess!=number and attempts == loops are useless, because you're either breaking out of them or incrementing attempts so their condition evaluates to False after the first iteration.
Guess 2 is never reached because either number equals guess (so number != guess is False) or attempts is still zero.
Guess 3 is never reached for the same reason. However, if guess 2 would be reached, guess 3 would never be reached because you put elif in front.
Try to get rid of the code for guess 2 and guess 3. Write all the code for guess = eval(input()) and if guess < number: ... elif guess > number: ... once and put it inside a loop. Here's a bit of pseudocode to illustrate the idea:
while attempts < 3
ask for user input
if guess equals number
print "you win"
exit the loop
else
print "that's wrong"
I used the "concatenation" method along with some of your helpful response ideas and finally got my code to work!! Thank you all so, so much for the help!! Here is the correct code for this program:
def guess():
from random import randint
number = randint(0,10)
print("I'm thinking of an integer, you have three guesses.")
attempts = 0
while attempts < 2:
guess = eval(input("Guess " + str(attempts + 1) + ": Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else:
print("You got it!")
break
else:
attempts == 3
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
else:
print("You got it!")
And then ending it with a call to function ("guess()"). Hope this serves well for those who experience this problem in the future. Again, thank you guys!
import random
def main():
the_number = random.randint(1,100)
guess = 0
no_of_tries = 0
while guess != the_number:
no_of_tries += 1
guess = int(input("Enter your guess: "))
if guess < the_number:
print "--------------------------------------"
print "Guess higher!", "You guessed:", guess
if guess == the_number - 1:
print "You're so close!"
if guess > the_number:
print "--------------------------------------"
print "Guess lower!", "You guessed:", guess
if guess == the_number + 1:
print "You're so close!"
if guess == the_number:
print "--------------------------------------"
print "You guessed correctly! The number was:", the_number
print "And it only took you", no_of_tries, "tries!"
if __name__ == '__main__':
main()
Right now, in my random number guessing game, if a person guesses lower or higher by one number, they receive the following message:
Guess lower! You guessed: 33
You're so close!
But I want to make it one sentence.
For example:
Guess lower! You guessed: 33. You're so close!
How would I implement this in my code? Thanks!
Simply put a comma (',') after your print statement if you want to avoid it advancing to the next line. For example:
print "Guess lower!", "You guessed:", guess,
^
|
The next print statement will add its output at the end of this line i.e., it will not move down to the start of the next line as you currently have.
Update re comment below:
To avoid the space due to the comma, you can use the print function. I.e.,
from __future__ import print_function # this needs to go on the first line
guess = 33
print("Guess lower!", "You guessed:", guess, ".", sep="", end="")
print(" You're so close!")
This will print
Guess lower!You guessed:33. You're so close!
This PEP also talks about the print function