# Little bit of confusion about else indentation

2276 views
4

Method 1:

``````n = 6
for i in range(2, n):
if n%i==0:
print 'Not Prime Number'
break
else:
print 'Prime Number'
``````

Output:

``````Not Prime Number
``````

Method 2:

``````n = 6
for i in range(2, n):
if n%i==0:
print 'Not Prime Number'
break
print 'Prime Number'
``````

Output:

``````Not Prime Number
Prime Number
``````

I want to know that "Method 1" is working absolutely fine but else indentation is not under the if statement so how is it working fine? Can anyone elaborate on this with a simple example? Note: this question was asked by interviewer

In your method 1, you should put the else part inside the for loop. Currently it is outside the for loop

Why is this tagged `java`?

6

Method 1 uses the optional `else` clause of a `for` loop. This clause is executed when a loop completes normally - i.e., `break` is not called.

See the documentation for additional details.

posted this
6

There are situations when you can use for/else, while/else, if/else. For example: Example 1:

``````for i in range(5):
print(i)
else:
print('hello world')
``````

output: 0 1 2 3 4 hello world

How to understand it? Simple, you have a 'for' loop, which will go through 0 to 4. But what happens when the loop ends? Well, this is when the else statement goes in. because you wrote than when it ends you'll print 'hello world'.

The trick is to see where the indentation is. In the previous example the else indentation match with the for loop so it will run when to loop finishes.

Example 2:

``````for i in range(5)
if i < 3:
print(i)
else:
print('hello world')
``````

output: 0 1 2 hello world hello world

Look how the indent of the else match with the if statement so it will run when the if statement goes false which is then i is higher than 3.

posted this
12

Python `for` has `else:` case which is executed at the end of the loop without a `break` (Normal `for` loop execution).

On normal execution of `for` loop, loop is terminated when iterator has no more elements i.e. `next()` on iterator fails. In this case, `else` part of `for` is executed.

``````for x in range(5):
print(x)
else:
print('Loop over without break!')  # This line is printed.
``````

Suppose you abruptly stop loop using a `break` statement, you exit out of the loop so the condition cannot evaluate to false and you never run the `else` clause.

``````for x in range(5):
print(x)
break
else:
print('Loop over with break!')  # This line is not printed.
``````

posted this