Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: for loop between if-else, how/why does this work?

I'm currently going through the Lynda Python tutorial and in the section on generators I see the following code:

def isprime(n):
    if n == 1:
        return False
    for x in range(2, n):
        if n % x == 0:
            return False
    else:
        return True

I didn't catch it at first, but as I was going through the code I noticed that the else keyword had an entire for-loop between it and an if at the same indentation level. To my surprise, the code not only runs, it actually produces the correct behavior.

If I were to replace the for-loop with a simple print("Hello, World") statement, only then do I get an expected interpreter error.

What was the reasoning behind this syntax, and why does it work with loop statements but not others like print()?

For reference, I would have expected the code to be written like the following:

def isprime(n):
    if n == 1:
        return False     
    for x in range(2, n):
        if n % x == 0:
            return False
    return True
like image 428
SiegeX Avatar asked Aug 11 '11 01:08

SiegeX


People also ask

Can you put a for loop in an if statement in Python?

Inside a for loop, you can use if statements as well.

What is the difference between for loop and if-else statement?

If Statements test a condition and then do something if the test is True. For Loops do something for a defined number of elements.

How do you combine for loop and if condition in python?

If you want to combine for loop with if-else statements, then you have to specify if-else in front of for loop. If the condition satisfies, then the if block will be executed, otherwise the else block will be executed. A for-loop takes a list or sequence of elements.

Can we use for loop in if condition?

No. The condition is evaluated ONCE when the code reaches the IF statement, and then the whole for loop would be executed without ever checking the condition again.


1 Answers

An else: block after a for: block only runs if the loop completed normally. If you break out of the loop, it won't run. In this case, this makes no difference because you never break out of the loop; you return before it ends or you let it complete normally.

like image 101
Jeremy Avatar answered Oct 03 '22 13:10

Jeremy