循环直到特定用户输入

10 投票
2 回答
123918 浏览
提问于 2025-04-17 06:14

我正在尝试写一个数字猜测程序,代码大概是这样的:

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

oracle()

我现在想做的是让这个一系列的if/elif/else命令循环,直到用户输入“正确”。也就是说,当程序给出的数字和用户心里的数字差不多的时候。不过,如果我不知道用户的数字,我就不知道该怎么写if语句,而我尝试用“while”也没有成功。

2 个回答

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 方法已经不存在了。

19

作为@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.

撰写回答