gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:16 25 4
gpt4 key购买 nike

演示了 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)

但我不知道该怎么做。

最佳答案

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

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)

关于python - 如何找到 while 循环执行了多少次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37613349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com