[Tutor] for loop

Alan Gauld alan.gauld at freenet.co.uk
Tue Apr 19 09:56:23 CEST 2005


> Well I was reading too fast (as usual) - you wanted to print 'yes'
> only if 5 is not in a sub list but you want to look in all the sub
> lists and yet print 'yes' only once???

Oops, me too, so in that case....

> So in long hand lets reverse the logic and make sure we print 'yes'
> only once
>
>  >>> yes = 0
>  >>> for num in x:
> ...   if 5 not in num:
> ...     if not yes:
> ...       print 'yes'
> ...       yes = 1
> ...
> yes

Or alternatively use the else construct of a for loop...

for num in x:
   if 5 in x:
      break
else: print 'yes'

The else only gets executed if the loop runs to completion
without a break...

HTH

Alan G.




More information about the Tutor mailing list