我刚刚开始学习http://learnpythonthehardway.org之后的课程。 在了解了循环和if语句之后,我想尝试制作一个简单的猜谜游戏。
问题是:
如果你做出了不正确的猜测,它就会卡住并且不断重复“太高”或“太低”,直到你达到crtl C为止。
我已阅读有关while循环的内容并阅读了其他人的代码,但我只是不想复制代码。
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"
答案 0 :(得分:8)
您必须再次询问用户。
在末尾添加此行(缩进四个空格以将其保留在while
块中):
guess = input("What could it be? > ")
这只是一个快速的黑客攻击。否则我会遵循@furins提出的改进。
答案 1 :(得分:3)
在while循环中移动请求可以解决问题:)
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"