[Tutor] For - if - else loop; print selective output

Alan Gauld alan.gauld at btinternet.com
Wed Oct 24 18:49:06 CEST 2012


On 24/10/12 17:27, Saad Javed wrote:

> a = [['jimmy', '25', 'pancakes'], ['tom', '23', 'brownies'], ['harry',
> '21', 'cookies']]

> for i in a:
>      if (i[1] == '25' or i[1] == '26'):
>          print 'yes'
> else:
>      print 'Not found'
>

> I want it to print "yes" for each positive match but nothing for a
> negative match.

So far so good.

> However if all matches are negative, I want it to print
> "Not found" once (That bit the code already does).

Only by accident, as you've seen it always prints that if the loop 
completes. You need to keep a record of any matches and test for that 
after the loop:

matched = False
for i in a:
    if ....
       print 'yes'
       matched = True

if not matched:
    print 'Not found'

I confess I'm not keen on the else part of a for loop and never use it, 
I think it leads to more confusion than anything. It doesn't do what 
most folks seem to expect, it should probably be called 'end' or 
something similar rather than 'else' IMHO.

 >>> for n in range(5):
...    print n,
... else:
...    print 'done!'
...
0 1 2 3 4 done!
 >>> for n in range(5):
...    if n < 3: print n,
...    else: break
... else: print 'done!'
...
0 1 2
 >>>


HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list