While / Else


#1

If the loop exits as the result of a break, the else will not be executed

But in python 3.6.0 IDLE i am running a code which is neglecting the above statement. and printing the else statement even after the break commands is executed.

while count < 5:
	if count == 5:
		break
	print (count)
	count = count + 1
else:
	print ("It did not happen")

0
1
2
3
4
It did not happen


#2

i ran i both python2 and python3, and both times the output was the same:

0
1
2
3
4
It did not happen

what is the problem?


#3

Loop is breaking as a result of "break" and therefore the else statement is printed on and therefore i am not able to understand. Why it is stated that "If the loop exits as the result of a break, the else will not be executed".

But here the else is getting executed??


#4

no, your loop simply ends because the condition becomes false. This is why else is executed.
look:

while count < 5:

This will only produces values lesser then 5. so how can this:

if count == 5:

ever be true? Your assumption of how the loop ends wasn't right


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.