我尝试根据我刚刚学到的东西编写一个完全独立的脚本,试着确保我理解它。在下面的代码中,我只是无法理解为什么,在猜测正确的随机数时,它永远不会到达我的ELSE:语句,打印猜测是否正确?我知道答案必须简单,但我只是感到困惑。
from sys import exit
import random
print "Guess the number between 1 thru 10"
print "You have 3 tries"
guess = raw_input("Enter a guess-->")
tries = 3
random_number = random.randrange(1,10)
while tries > 1 and guess != random_number:
print "That's not the number, try again!"
print "Tries remaining:", tries - 1
guess = raw_input("Next guess?-->")
tries = tries - 1
if guess != random_number:
print "Sorry, you lose!"
print "The number was", random_number
exit(0)
else:
print "You guessed it!"
答案 0 :(得分:-2)
您需要将guess
与int
进行比较。 raw_intput
从输入中读取一行并将其转换为字符串。
from sys import exit
import random
print "Guess the number between 1 thru 10"
print "You have 3 tries"
guess = raw_input("Enter a guess-->")
tries = 3
random_number = random.randrange(1,10)
while tries > 1 and int(guess) != random_number:
print "That's not the number, try again!"
print "Tries remaining:", tries - 1
guess = raw_input("Next guess?-->")
tries = tries - 1
if int(guess) != random_number:
print "Sorry, you lose!"
print "The number was", random_number
exit(0)
else:
print "You guessed it!"