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

Don Jennings dfjennings at gmail.com
Wed Oct 24 19:19:53 CEST 2012


On Oct 24, 2012, at 12:27 PM, tutor-request at python.org wrote:

> Hi,
> 
> 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'

Suggestion:  use names which are meaningful.

> 
> This prints:
> yes
> not found

I'd be very surprised by that. What it should print is:
yes
Not found

(Note the capital letter at the beginning of the last line.)

> 
> I want it to print "yes" for each positive match but nothing for a negative
> match. However if all matches are negative, I want it to print "Not found"
> once (That bit the code already does).

Yes, it prints that text, but do you understand why it does? It's not because two of the items do not match your if statement.

> I do I get it to print "yes" only in
> a mix result situation?

While there are lots of ways to approach this exercise, I suggest that you try this:  first, go through the list as you are doing now, checking if any of the items (are these ages, perhaps?) are a "positive match", appending a "yes" to another list (do you know how to create an empty list and append to it?). Then, if that list is not empty, you'll print 'yes' for every item, else you'll print the "Not found" once. For the latter, here is some code to get you started:

people = ['Sally', 'Bob']

if people:
    print "this list contains something"
else:
    print "this list is empty"

Take care,
Don


More information about the Tutor mailing list