繁体   English   中英

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

[英]Counter in for loop and resetting counter

我有以下代码:

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

你可以这样做:

x = 0
for x in range(10):
     num = int(input("enter an integer: "))
     x += 1
     if x == 10:
         print("10")
         x = 0
     else:
         pass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM