循环直到特定用户输入

时间:2011-11-13 20:09:15

标签: python loops numbers

我正在尝试编写一个数字猜测程序,如下所示:

def oracle():
n = ' '
print 'Start number = 50'
guess = 50 #Sets 50 as a starting number
n = raw_input("\n\nTrue, False or Correct?: ")
while True:
    if n == 'True':
        guess = guess + int(guess/5)
        print
        print 'What about',guess, '?'
        break
    elif n == 'False':
        guess = guess - int(guess/5)
        print
        print 'What about',guess, '?'
        break
    elif n == 'Correct':
        print 'Success!, your number is approximately equal to:', guess

预言()

我现在要做的是让这个if / elif / else命令序列循环,直到用户输入'Correct',即当程序声明的数字大约等于用户数时,但是如果我不知道用户号码我想不出如何实现和if语句,我尝试使用'while'也行不通。

2 个答案:

答案 0 :(得分:13)

作为@Mark Byers方法的替代方法,您可以使用while True

guess = 50     # this should be outside the loop, I think
while True:    # infinite loop
    n = raw_input("\n\nTrue, False or Correct?: ")
    if n == "Correct":
        break  # stops the loop
    elif n == "True":
        # etc.

答案 1 :(得分:2)

您的代码无效,因为您在首次使用之前尚未向n分配任何内容。试试这个:

def oracle():
    n = None
    while n != 'Correct':
        # etc...

更易读的方法是将测试移至以后并使用break

def oracle():
    guess = 50

    while True:
        print 'Current number = {0}'.format(guess)
        n = raw_input("lower, higher or stop?: ")
        if n == 'stop':
            break
        # etc...

Python 2.x中的input读取一行输入,然后评估。您想使用raw_input

注意:在Python 3.x中,raw_input已重命名为input,而旧的input方法已不再存在。