I want to have a user try a guessing game. The program should loop until the user guesses right.
How can I compare the values? Right now its going through the else part every time, even when the user guesses right.
Here is the code;
import sys
from random import randint
secret_number = randint(0, 100)
num_guesses = 0
guess = 0
while guess != secret_number:
guess = raw_input("Enter a number: ")
if (guess < secret_number):
print "Your guess is too low. Please try again."
else:
print "Your guess is too high. Please try again."
num_guesses = num_guesses + 1
print "Thank you, you guessed right"
print guess
You need to convert the string that raw_input returns into an integer using int, so the comparison operator works the way you expect it to:
guess = int(raw_input("Enter a number: "))
raw_input will return string, you compare string with int and nothing works
also you will never guess the number:
your code hav 2 options: too low or too high
also you never compare tries with max tries (try to fix that by yourself)
corrected version:
import sys
from random import randint
secret_number = randint(0, 100)
num_guesses = 0
guess = 0
while guess != secret_number:
guess = raw_input("Enter a number: ")
if (int(guess) < secret_number):
print "Your guess is too low. Please try again."
elif (int(guess) > secret_number) :
print "Your guess is too high. Please try again."
else:
print "Thank you, you guessed right"
break
num_guesses = num_guesses + 1
print guess
Related
I am trying to add an error when a string is entered instead of an integer. I've looked at other similar posts but when I try and implement it into my code it keeps spitting errors out. I have a number guessing game between 1 and 50 here. Can't for the life of me figure out what's wrong.
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") )
break
except ValueError:
print("Please input a number.")**
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
Note that you're asking three times for the exact same input. There is really no need for that and no need for two loops at all. Just set the guess to a default value that will never be equal to the number (None) and use one single input, wrapped with try/except:
import random
number = random.randrange(1, 50)
guess = None
while guess != number:
try:
guess = int(input("Guess a number between 1 and 50: "))
except ValueError:
print("Please input a number.")
else:
if guess < number:
print("You need to guess higher. Try again.")
elif guess > number:
print("You need to guess lower. Try again.")
print("You guessed the number correctly!")
You could try running a while loop for the input statements. Checking if the input(in string format) is numeric and then casting it to int.
Sample code:
a = input()
while not a.isnumeric():
a = input('Enter a valid integer')
a = int(a)
The code executes until the value of a is an int
your code did not work because the indentation is not right
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") ) # here
break # here
except ValueError: # here
print("Please input a number.")
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
Output
Guess a number between 1 and 50: aa
Please input a number.
Guess a number between 1 and 50: 4
You need to guess higher. Try again.
The objective is to create a simple program that generates a number between 1 and 100, it will then ask the user to guess this, if they guess outside of the number range it should tell them to guess again, if not it should tell them whether their guess was too high or too low, prompting them to guess again. Once they do guess the correct number it should tell them they've won and the number of tries it took for them to guess it correctly.
Here is what I have so far
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
return play_game
else:
print("Invalid number.")
return play_game()
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
The issue I'm currently running into is when it checks to see if their guess was between 1-100 instead of moving on to weather or not their number was too how or to low, it stays and loops.
If anyone could help me with this issue and review the code in general I'd appreciate it.
I think the problem is with some indentation and some logical problems in the flow.
When you call play_game() from inside the game, it starts a completely different game
with different random_number.
A good code that satisfies your condition might look like the following
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
else:
print("Invalid number.")
play_game()
You could re-adjust your code:
1. if no. within range, run your high, low, match checks
2. break if guess matches the no
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 0
while True:
count += 1
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
break
else:
print("Invalid number, try again")
play_game()
The issue you are running into is because of incorrect indentation. The if-else statements that check whether the number is within the valid range are at the same indentation level as the while loop and thus are not executed within it. Simply indenting should fix the problem.
Furthermore, you have called play_game without parenthesis, making it incorrect syntax for a function call. However, rather than checking if the number is greater than 0 and lesser than 100, it would more optimal to check whether number is lesser than 0 or greater than 100, and if that is the case, print invalid number and call play_game().
It would look something like this:
while True:
if guess < 0 and guess > 100:
print ("Invalid number.")
return play_game()
The rest of your code looks good. I've also attached the link on the section of indentations of the Python documentation here.
import random
number = random.randint(0,10)
#print (number)
guess = int(input("I'm thinking of a number between 1 and 10. \nPlease guess what it is: "))
#print(guess)
while guess != number:
if guess > number:
print("That is too high!")
guess = int(input())
elif guess < number:
print("That is too low")
guess = int(input())
else:
print("Thats it! You win!")
I'm working out a few python coding examples and I am confused why my else statement isn't printing?
The code objective is to generate a random number, and then have the user input a guess and then depending if the guess is lower or higher than the random number for the computer to notify the user and if the user guess correctly, then to tell the user that they won.
I'm tested this out and when I input the correct number the code just ends and doesn't print out "That's it! You win!". Why is this and how can I get it to print it out?
Guess input prior to the loop will most times be different than the number to guess, therefore the loop will not enter.
You also have other more subtle bugs: for instance, input is taken twice in one loop, creating conditions for improper feedback. Further, your win is confirmed by default, that is if guess not too high, and if guess not too low, then it is a win; a positive assertion such as if guess equals number, is probably safer to declare a win.
Here is a design that segregates each actions in one place in the loop, minimizing the risks of a faulty logic.
import random
number = random.randint(0, 10)
guess = None
while guess != number:
guess = int(input())
if guess > number:
print("That is too high!")
elif guess < number:
print("That is too low")
elif guess == number:
print("Thats it! You win!")
else:
print('that was not supposed to happen')
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!
I have only just started to learn to program following http://learnpythonthehardway.org.
After learning about loops and if-statements I wanted to try to make a simple guessing game.
The problem is:
If you make an incorrect guess it gets stuck and just keeps repeating either "TOO HIGH" or "TOO LOW" until you hit crtl C.
I have read about while loops and have read other peoples code but I simply dont want to just copy the code.
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
guess = input("What could it be? > ")
correct = False
while not correct:
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TOO HIGH"
elif guess < random_number:
print "TOO LOW"
else:
print "Try something else"
You have to ask the user again.
Add this line at the end (indented by four spaces to keep it within the while block):
guess = input("What could it be? > ")
This is just a quick hack. I would otherwise follow the improvement proposed by #furins.
Moving the request inside the while loop does the trick :)
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
correct = False
while not correct:
guess = input("What could it be? > ") # ask as long as answer is not correct
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TO HIGH"
elif guess < random_number:
print "TO LOW"
else:
print "Try something else"