[Tutor] For - if - else loop; print selective output
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:
> a = [['jimmy', '25', 'pancakes'], ['tom', '23', 'brownies'], ['harry',
> '21', 'cookies']]
> for i in a:
> if (i == '25' or i == '26'):
> print 'yes'
> print 'Not found'
Suggestion: use names which are meaningful.
> This prints:
> not found
I'd be very surprised by that. What it should print is:
(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']
print "this list contains something"
print "this list is empty"
More information about the Tutor