for循环中的计数器并重置计数器

斯拉蒂巴特法斯特

我有以下代码:

for i in range(10):
    while True:
       num = int(input("Enter an integer: "))
       print("The double of",num,"is",2 * num)
    print('10')

我想要做的是在 10 次迭代后,消息应该打印 10。它这样做但只有一次,我如何重置计数器以便它在达到 10 后重新启动?

我希望程序做的是在 10 次迭代后打印“10”,但循环是无限的,所以它永远不会中断。

马西里努扎基

您可以使用它,您只需循环一次并检查计数器是否可以被 10 整除以打印消息

for i in range(1, 100):
    num = int(input("Enter an integer: "))
    print("The double of",num,"is",2 * num)
    if i%10==0:
        print('10')

如果你想要无限循环:

i = 1
while True:
    num = int(input("Enter an integer: "))
    print("The double of",num,"is",2 * num)
    if i%10==0:
        print('10')
    i+=1

结果是for i in range(1,21)将是

The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
10
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
The double of 50 is 100
10

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章