[Tutor] for loop
Gustavo Campanelli
gcampanelli at ciudad.com.ar
Wed Jan 7 18:49:52 EST 2004
Ron A wrote:
>I'm experimenting and would like 'yes' to be printed only if 5 is not in
>the list, but I want to look in each list. This prints out two yeses.
>How do I get it to print just one 'yes'?
>
>x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
>
>for num in x:
> if 5 in num:
> break
> else:
> print 'yes'
>
>
>
This code goes to the first list, checks if 5 is there, and as it's not,
prints a yes (when there is no 5 there), then enters the second, sees
it's not there and prints another yes, goes to the third and as 5 is in
there breaks and doesn't do anything more. The code does, in other
words, exactly what you told it to do, but not what you intended. This
should do the trick, you had the if evaluating things the oposite way as
you intended :)
x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
for num in x:
if 5 in num:
print 'yes'
break
Gedece, still a python newbie
More information about the Tutor
mailing list