n = 6 for i in range(2, n): if n%i==0: print 'Not Prime Number' break else: print 'Prime Number'
Not Prime Number
n = 6 for i in range(2, n): if n%i==0: print 'Not Prime Number' break print 'Prime Number'
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
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.
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.
else: case which is executed at the end of the loop without a
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
for x in range(5): print(x) break else: print('Loop over with break!') # This line is not printed.