[Tutor] for loop

Lloyd Kvam pythontutor at venix.com
Thu Jan 8 11:14:35 EST 2004


The intent of the programmer may have been to print yes if there
was any group with no 5.  For that intent the break was placed with
the wrong conditional branch.

This is a minimal change to fix it.
 >>>x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
 >>>
 >>>for num in x:
 >>>    if 5 in num:
	   pass
 >>>    else:
 >>>        print 'yes'
 >>>        break

I got hung up reading the original code.  The code has two features:
	1. yes implies there is a group with NO 5 (and Ron only wants one yes)
	2. we stop looking once we encounter a group with a 5

Combining those ideas, we no longer need the loop.  If the first group
contains a 5 we stop looking (#2).  If the first group does not contain
a five, print yes satisfying #1.



Daniel Ehrenberg wrote:

> Lloyd Kvam wrote:
> 
>>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
> 
> 
> Are you sure that's what he intended to do? Your code
> checks only the first list in x, but I think he wanted
> to check them all. I would impliment it like this
> instead:
> 
> x = [[1,2,3],[2,4,6],[8,4,5,6],[9,8,7]]
> contains5 = False
> 
> for num in x:
>     if 5 in x:
>         contains5 = True
>         break
> 
> if contains5: print 'yes'
> 
> You still need to loop through x to access each list.
> 
> Daniel Ehrenberg
> 
> __________________________________
> Do you Yahoo!?
> Yahoo! Hotjobs: Enter the "Signing Bonus" Sweepstakes
> http://hotjobs.sweepstakes.yahoo.com/signingbonus
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
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