1

我才刚刚开始按照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"
4

2 回答 2

8

您必须再次询问用户。

在末尾添加这一行(缩进四个空格以将其保留在while块内):

    guess = input("What could it be? > ")

这只是一个快速破解。否则我会遵循@furins 提出的改进。

于 2012-12-17T15:34:20.130 回答
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"
于 2012-12-17T15:41:06.740 回答