如何让用户在Python中重试?

时间:2013-10-12 15:09:25

标签: python

我的朋友让我用Python为她的班级做一个简单的数学测试。当用户出错时,问题将无限重复。

 test1 = raw_input ("How much is 3+23?")
if (test1 == '26'):
    print "Well done!"
else:
    print "Try again. I'm sure your brain will function correctly this time."
    test1 = raw_input ("How much is 3+23?")

我试过这样做,但这个问题只重复了两次。有没有办法进行无限重试而不必输入“game1 = raw_input(”多少是3 + 23?“)”一遍又一遍?

此外,一些问题可能只有有限的重试次数。我可以告诉Python我希望这部分代码循环多少次?

提前致谢!

1 个答案:

答案 0 :(得分:3)

对于无限循环,请使用while-loop

# This will run until input = '26'
while True:
    test = raw_input("How much is 3+23?")
    if test == '26':
        # If we got here, input was good; break the loop
        break
    print "Try again. I'm sure your brain will function correctly this time."
print "Well done!"

对于有限数量的循环,请使用for-loopxrange

# This runs for 10 times max
for _ in xrange(10):
    test = raw_input("How much is 3+23?")
    if test == '26':
        print "Well done!"
        break
    print "Try again. I'm sure your brain will function correctly this time."