Home > database >  infinite loops of for loop in python can be done?
infinite loops of for loop in python can be done?

Time:01-21

how many times we can execute the print statement?

for i in range (1,6,-1):
   print(done)

The answer is none. But in C language if we write this code it runs in infinite mode. Why?

int i;
for (i=5; i<=10; i--)
 {
     printf("what happens");
 }

I tried in python, it didnt even run but in C it ran infinite times, why?

CodePudding user response:

The equivalent expression for the second code snippet in Python would be

i = 5

while i <= 10:
   print('what happens')
   i -= 1

Since i decreases by one every cycle and never goes above 10, the loop never exits.

CodePudding user response:

There's a fundamental difference between Python and C for loops:

As already suggested:

  1. The C example in your snippet is not infinite, but relies on wrap around math (when an integral type bound is exceeded), and (for most implementations) will execute 232 - 5 times.
    If you want a truly infinite loop in C, use: for (;;)

  2. You could use a while loop instead

Due to the nature of Python's for loop, your desired behavior can't be replicated OOTB. But there are tricks (converting a while into a for).
And this can be done via [Python.Docs]: itertools.cycle(iterable):

>>> import itertools as its
>>>
>>>
>>> it = its.cycle([None])  # Infinite iterable
>>>
>>> next(it)
>>> next(it)
>>> next(it)
>>> next(it)
>>>
>>> for _ in it:
...     if input("Press 'n' to exit: ").lower() == "n":
...         break
...
Press 'n' to exit: y
Press 'n' to exit: 
Press 'n' to exit: A
Press 'n' to exit: Y
Press 'n' to exit: t
Press 'n' to exit: 1.618
Press 'n' to exit: sdf54
Press 'n' to exit: n
>>>
  • Related