-2

我的朋友让我用 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 我希望这部分代码循环多少次吗?

提前致谢!

4

1 回答 1

4

对于无限循环,请使用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 循环xrange

# 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."
于 2013-10-12T15:13:19.010 回答