1

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

Rashid Aziz
  • 29
  • 1
  • 9

3 Answers3

4

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

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.

Snedecor
  • 689
  • 1
  • 6
  • 14
1

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 completed 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.
Austin
  • 25,759
  • 4
  • 25
  • 48