如何找到while循环执行了多少次?

时间:2016-06-03 11:35:31

标签: python loops while-loop

示例程序中显示了while循环:

answer="0"
while answer!="4":
    answer=input("What is 2 + 2?")
    if answer!="4":
        print("Wrong...Try again.")
    else:
        print("Yes! 2 + 2 = 4")

这里循环将执行,直到用户给出正确的答案,即4。

我想在上面的代码中添加另一个功能,它打印用户尝试给出正确答案的次数。

print("You gave correct answer in attempt",answer)

但我不知道该怎么做。

3 个答案:

答案 0 :(得分:2)

创建一个存储用户尝试次数的变量:

attempts = 0 

while True:
    answer = int(raw_input("What is 2 + 2?"))
    attempts += 1
    if answer == 4: 
        print("Yes! 2 + 2 = 4")
        break
    print "Wrong.. try again"

print "It took {0} amount of attempts".format(attempts)

答案 1 :(得分:2)

while - 循环转换为for - 循环:

from itertools import count

for attempts in count(1):
    answer = input("What is 2 + 2?")
    if answer == "4":
        break
    print("Wrong...Try again.")
print("Correct in {} attempts!".format(attempts))

答案 2 :(得分:0)

目前正在编写Python的一些教程,所以如果它不起作用,请原谅我的n00b级...

answer=0
attempts = 0
while answer!=4:
    answer=input("What is 2 + 2?")
    if answer!=4:
        print("Wrong...Try again.")
        attempts = attempts + 1
    else:
        print("Yes! 2 + 2 = 4")

print("You gave correct answer in %d attempts" % attempts)