2012-12-17 104 views
1

我刚刚开始学习编程以下http://learnpythonthehardway.org。 了解循环和if语句后,我想尝试做一个简单的猜谜游戏。python中的猜测游戏

的问题是:

如果做出不正确的猜出它卡住,只是不断重复,无论是“过高”或“太低”,直到你击中CRTL C.

我看了一下,而循环和阅读其他人的代码,但我只是不想复制代码。

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

是LPTHW真教人使用'输入()'在Python 2的伎俩? – geoffspear

+0

您需要在'while not correct:'循环中再次提示用户; Eumiro的方法是最好的:)。另外,我认为'random.randrange(1,10)'会得到一个从1到9的随机范围,因为最后一个数字可能是唯一的。我不确定是否是这样;在正常的对象类型中,范围(1,10)仅为1到9;它排除了第二个参数。 –

+0

@ F3AR3DLEGEND是正确的:random.randrange(start,stop [,step])在start <= number furins

回答

8

您必须再次询问用户。

末加入这一行(由四个空格缩进,以保持它的while块内):

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

这仅仅是一个快速的黑客。否则我会遵循@furins提出的改进。

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" 
+0

ops,它几乎与@eumiro的答案是一样的......但是,在while循环的开始处提出这个问题可以让你不重复自己。对不起,重复 – furins

+0

,这是一个更好的答案。 – eumiro