[Tutor] for loop

Lloyd Kvam pythontutor at venix.com
Wed Jan 7 19:02:26 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 prints yes until it finds a num list that contains 5.

To stop printing yes after the first time, simply break after printing
yes.  However, this is equivalent to simply checking the first element
of x.  You no longer need the loop.  So now the equivalent code is:

if 5 not in x[0]:
	print "yes"

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list