y 增量后执行 x

我想做一些事情之后iis 20,40等等。


例如:


i = 0

while True:

    i+=1

    if i == # increment of 20 (40, 60, 80, etc.):

        # do this


慕尼黑8549860
浏览 117回答 2
2回答

翻阅古今

选项 1 和 2 使用模运算符来检测何时i是 的乘法20,但效率较低,因为会发生不必要的迭代。选项 3 使用range, 并且效率更高,因为只会发生必要的迭代。选项1用途not i % 20:i = 0while True:    i+=1    if not i % 20:        print(i)选项2用途0 == i % 20:i = 0while True:    i+=1    if 0 == i % 20:        print(i)选项 3:For 循环使用范围:从 开始20直到threshold跳跃20threshold = 10000for i in range(20, threshold, 20):    print(i)

阿波罗的战车

i = 0while True:    i+=1    if i % 20 == 0: # increment of 20 (40, 60, 80, etc.):        print(i) #or something else输出:20406080...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python