I want to do something after i
is 20
, 40
, etc.
For example:
i = 0
while True:
i+=1
if i == # increment of 20 (40, 60, 80, etc.):
# do this
I want to do something after i
is 20
, 40
, etc.
For example:
i = 0
while True:
i+=1
if i == # increment of 20 (40, 60, 80, etc.):
# do this
i = 0
while True:
i+=1
if i % 20 == 0: # increment of 20 (40, 60, 80, etc.):
print(i) #or something else
Output:
20
40
60
80
...
Options 1 & 2 uses the modulus operator, to detect when i
is a multiplication of 20
, are less efficient as unnecessary iterations will happen.
Option 3 uses range
, and more efficient as only necessary iterations will happen.
Option 1
Use not i % 20
:
i = 0
while True:
i+=1
if not i % 20:
print(i)
Option 2
Use 0 == i % 20
:
i = 0
while True:
i+=1
if 0 == i % 20:
print(i)
Option 3 : For Loop
Using range: start from 20
till threshold
in jumps of 20
threshold = 10000
for i in range(20, threshold, 20):
print(i)