Custom Search

Saturday, April 16, 2011

python for else statements

The "else" block will be normally executed at the end of the for loop or the break is called or list is empty.

lst = [1,2,0,3,4]
for x in lst:
print "-----for-----",x
else:
print "----else----", x

Output
====
-----for----- 1
-----for----- 2
-----for----- 0
-----for----- 3
-----for----- 4
----else---- 4

=============

lst = []
for x in lst:
print "-----for-----",x
else:
print "----else----", x

Output
====
----else----
Traceback (most recent call last):
File "del me.py", line 8, in
print "----else----", x
NameError: name 'x' is not defined



No comments:

Post a Comment