Trying to do a simple guessing game program in python, but I'm more comfortable in java. When the correct number is entered, it says it is too high and won't exit the while loop. Any suggestions?
import random
comp_num = random.randint(1,101)
print comp_num
players_guess = raw_input("Guess a number between 1 and 100: ")
while players_guess != comp_num:
if players_guess > comp_num:
print "Your guess is too high!"
elif players_guess < comp_num:
print "Your guess is too low!"
players_guess = raw_input("Guess another number between 1 and 100: ")
print "CONGRATULATIONS! YOU GUESSED CORRECTLY!"
5 Answers 5
I would guess it is because you are comparing string and int. Whatever is captured from raw_input is captured as a string and, in Python:
print "1" > 100 # Will print true
For it to work, convert:
players_guess = raw_input("Guess a number between 1 and 100: ")
to
players_guess = int(raw_input("Guess a number between 1 and 100: "))
5 Comments
raw_input to an int... like your updated question indicates. You should not update your question with answers, since you're only confusing things.raw_input at the bottom of the loop.You are comparing a string to an int. That's why you get odd results.
Try this:
players_guess = int(raw_input("Guess a number between 1 and 100: "))
Comments
import random
comp_num = random.randint(1,101)
print comp_num
players_guess = int(raw_input("Guess a number between 1 and 100: "))
while players_guess != comp_num:
if players_guess > comp_num:
print "Your guess is too high!"
elif players_guess < comp_num:
print "Your guess is too low!"
players_guess = int(raw_input("Guess another number between 1 and 100: "))
print "CONGRATULATIONS! YOU GUESSED CORRECTLY!"
you need to force the input to int
3 Comments
Try this code:
import random
comp_num = random.randint(1,101)
print comp_num
players_guess = int(raw_input("Guess a number between 1 and 100: "))
while players_guess != comp_num:
if players_guess > comp_num:
print "Your guess is too high!"
elif players_guess < comp_num:
print "Your guess is too low!"
players_guess = int(raw_input("Guess another number between 1 and 100: "))
print "CONGRATULATIONS! YOU GUESSED CORRECTLY!"
1 Comment
in your code change in print formation and use 'int' datatype in numerical argument. i will change the cond so try it once:
import random
comp_num = random.randint(1,101)
print ('comp_num')
players_guess = int(raw_input("Guess a number between 1 and 100: "))
while players_guess != comp_num:
if players_guess > comp_num:
print('Your guess is too high!')
elif players_guess < comp_num:
print('Your guess is too low!')
players_guess = int(raw_input("Guess another number between 1 and 100: "))
print('CONGRATULATIONS! YOU GUESSED CORRECTLY!')
eliffor the secondif...