-1

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 
6
  • 2
    Use if (i % 20) == 0 Commented Aug 28, 2020 at 20:40
  • isn't there a more elegant way of doing it? Commented Aug 28, 2020 at 20:40
  • 3
    if i % 20 == 0:? Commented Aug 28, 2020 at 20:41
  • 1
    for i in range(20, x, 20): where x is at what value you want to stop (assuming you don't do anything else when the condition isn't true) Commented Aug 28, 2020 at 20:41
  • 1
    What is inelegant about if i % 20 == 0? Commented Aug 28, 2020 at 20:44

2 Answers 2

1

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

sys.maxsize huh?
1
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 ... 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.