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:
Python: loop is performed on the elements of a (finite) sequence and continues as long there are elements left in it ([Python.Docs]: Compound statements - The for statement)
C: loop continues as long a condition is met ([CPPReference]: for loop). To replicate the sequence iteration behavior, some languages have foreach
As already suggested:
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 (;;)
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 >>>