如何防止布尔while循环中的无限循环?

时间:2012-10-28 22:03:42

标签: while-loop boolean infinite-loop

我的代码如下:

maybeYes = raw_input("Please enter Yes to continue.")
    if maybeYes != "Yes":
        print "Try again."
        # ask for input again
    else:
        pass

我想填写哪些内容再次要求输入?

3 个答案:

答案 0 :(得分:2)

你应该直接在循环中执行raw_input。

while True:
    result = raw_input("...")
    if result != "Yes":
        print "Try again."
        continue
    else:
        break

答案 1 :(得分:2)

这将循环打印wrong,直到用户输入yesYesYEsYESyEs或{{1}在检查yeS之前输入被转换为全部大写,那么你的代码可以继续......

YES

输出:

while raw_input("Please enter Yes to start: ").upper() != 'YES':
       print 'Wrong'

print 'Correct'

#Carry on here 

答案 2 :(得分:1)

在我看来,你想要一个无限循环。

maybeYes = raw_input("Please enter Yes to continue.")
while maybeYes != "Yes":
    maybeYes = raw_input("Please try again.")

但是,您始终可以添加计数器/转义符。

maybeYes = raw_input("Please enter Yes to continue.")
attempts = 0
while maybeYes != "Yes" and attempts < 10:
    maybeYes = raw_input("Please try again.")
    attempts += 1