Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Back and forth loop Python

Tags:

I want to create an infinite loop that counts up and down from 0 to 100 to 0 (and so on) and only stops when some convergence criterion inside the loop is met, so basically something like this:

for i in range(0, infinity):     for j in range(0, 100, 1):         print(j) # (in my case 100 lines of code)     for j in range(100, 0, -1):         print(j) # (same 100 lines of code as above) 

Is there any way to merge the two for loops over j into one so that I don't have write out the same code inside the loops twice?

like image 315
Daniel Avatar asked Sep 05 '18 14:09

Daniel


People also ask

How do you go back a loop in Python?

The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops.

How do you repeat 3 times in Python?

The Python for statement iterates over the members of a sequence in order, executing the block each time. Contrast the for statement with the ''while'' loop, used when a condition needs to be checked each iteration or to repeat a block of code forever. For example: For loop from 0 to 2, therefore running 3 times.

What are the 3 loops in Python?

The three types of loop control statements are: break statement. continue statement. pass statement.

Is there a repeat loop in Python?

Overview. Looping allows you to run a group of statements repeatedly. Some loops repeat statements until a condition is False; others repeat statements until a condition is True. There are also loops that repeat statements a specific number of times.


1 Answers

Use the chain method of itertools

import itertools for i in range(0, infinity):     for j in itertools.chain(range(0, 100, 1), range(100, 0, -1)):         print(j) # (in my case 100 lines of code) 

As suggested by @Chepner, you can use itertools.cycle() for the infinite loop:

from itertools import cycle, chain  for i in cycle(chain(range(0, 100, 1), range(100, 0, -1))):     .... 
like image 186
damienfrancois Avatar answered Sep 22 '22 17:09

damienfrancois