Sriram Sriram - 3 months ago 6
Python Question

How to add a condition in Python for loop

In Java, the FOR loop syntax offers a place where we can add a condition. For instance, in the below code the condition is i*j < n

for (i=0; i*j < n; i++)
{ ... }


In Python, how can we add such condition in the for loop statement?

for i in range(n):


I know that we can add an if statement inside the for loop, but I am concerned that it will increase the run time to O(n). Please advice.

Answer

the for has a complexity of O(n), so a if does not change the complexity.

The for(i=0; i*j < n; i++) in Java is represented by while in Python:

i = 0  # initialization
while i * j < n:  # conditions
   do_something
   i += 1  # step