Ethan Furman wrote:
Sandy wrote:
Hi all,
A simple and silly if-else question.
I saw some code that has the following structure. My question is why
else is used there though removing else
has the same result. More important, is it not syntactically wrong :-(
for i in xrange(8):
if i < 4:
print i
else:
print i
Cheers,
dksr
The else is not tied to the if, it is tied to the for. The statements
in a for-else (and while-else, and if-else) only execute if the control
expression becomes False. If you want to avoid executing the else
clause, you have to break out of the loop.
Some examples:
In [1]: for i in xrange(8):
...: if i < 4:
...: print i
...:
0
1
2
3
In [2]: for i in xrange(8):
...: if i < 4:
...: print i
...: else:
...: print i
...:
0
1
2
3
7
In [3]: for i in xrange(8):
...: if i < 4:
...: print i
...: if i == 1:
...: break
...: else:
...: print i
...:
0
1
Hope this helps!
The example that makes it clearest for me is searching through a list
for a certain item and breaking out of the 'for' loop if I find it. If I
get to the end of the list and still haven't broken out then I haven't
found the item, and that's when the else statement takes effect:
for item in my_list:
if item == desired_item:
print "Found it!"
break
else:
print "It's not in the list"
--
http://mail.python.org/mailman/listinfo/python-list