Interesting “else” clause in “for” loop in Python.

In this post, we will look at an interesting feature of “for” loop in Python.

In Python, we have a special clause known as “else” with for loop.

This “else” condition executes in the end when “for” loop condition fails.

To understand this, lets take an example.

1. Create a python program with for loop and else condition.

user@ngelinux$ cat else_loop.py 
#!/usr/bin/python
i=6
for i in range(1,5):
	print i
else:
	print "This is printed in the end when above condition fails"
user@ngelinux$ 

2. Output

user@ngelinux$ ./else_loop.py 
1
2
3
4
This is printed in the end when above condition fails
user@ngelinux$ 

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments