【问题标题】:While loop not terminating properly虽然循环没有正确终止
【发布时间】:2016-06-20 16:55:52
【问题描述】:

所以我得到了这个代码,它会猜测 0 到 100 之间的数字。 它提示一个数字,用户用'h''l'或'c'回答

现在一切正常,除了我希望此行仅在用户输入不等于“h”、“l”或“c​​”时显示,而不是现在即使我输入“c”也会显示它会中断循环,对吧?

print "Sorry, I did not understand your input."

完整代码

start = 0
end = 100
guess = int((start+end)/2.0)
print "Please think of a number between 0 and 100!"
print


x= 'n'

while x != 'c':

    print 'Is your secret number ' + str(guess) + '?'
    x = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.").lower()
    if x == 'h':
        end = guess
    elif x == 'l':
        start = guess
    else: 
        print "Sorry, I did not understand your input."
guess = int((start + end)/2)

print 'your answer is: ' + str(guess)  

所以为了澄清这是即使我输入'c'时的输出

Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess     is too low. Enter 'c' to indicate I guessed correctly.c

Sorry, I did not understand your input.

你的答案是:50

【问题讨论】:

    标签: python-2.7 while-loop


    【解决方案1】:

    'c' 的情况没有elif,所以它属于最后的else

    添加以下内容来处理这种情况并打破 while 循环:

    elif x == 'c':
        break
    

    此外,您可以只执行while True: 并循环直到c 中断。

    你的高/低逻辑也是落后的。对于h,例如 start = guess。

    guess 的更新应该在 while 循环内缩进。

    【讨论】:

    • 谢谢!现在我终于明白那个break是用来做什么的了,我很困惑。现在我终于可以继续我的课程了。太爱了!
    猜你喜欢
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2011-01-19
    • 2023-03-28
    • 1970-01-01
    • 2013-04-22
    相关资源
    最近更新 更多