13. Python basics: else after while

The else clause is only executed when your while condition becomes false. If you break out of the loop it won’t be executed.

The following loop will run the else code:

x = 0
while x < 5:
    x += 1
    print (x)
else:
    print ('Else statement has run')
print ('End')

OUT:

x = 0

while x < 5:

    x += 1

    print (x)

else:

    print ('Else statement has run')

print ('End')

OUT:

1
2
3
4
5
Else statement has run
End

The following loop with a break will not run the else code:

x = 0
while x < 5:
    x += 1
    print (x)
    if x >3:
        break
else:
    print ('Else statement has run')
print ('End')

OUT:

1
2
3
4
End

 

One thought on “13. Python basics: else after while

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s