尝试在python中做一个简单的猜谜游戏程序,但我在java中更舒服。 输入正确的数字后,表示它太高并且不会退出while循环。 有什么建议吗?
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!"
答案 0 :(得分:7)
我猜是因为您正在比较string
和int
。从raw_input
捕获的任何内容都被捕获为string
,并在Python中:
print "1" > 100 # Will print true
要使其正常工作,请转换:
players_guess = raw_input("Guess a number between 1 and 100: ")
到
players_guess = int(raw_input("Guess a number between 1 and 100: "))
答案 1 :(得分:5)
您正在将字符串与int进行比较。这就是你得到奇怪结果的原因。
试试这个:
players_guess = int(raw_input("Guess a number between 1 and 100: "))
答案 2 :(得分:0)
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!"
你需要强制输入int
答案 3 :(得分:0)
试试这段代码:
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!"