newbie question: for loop within for loop confusion

Roy Smith roy at panix.com
Sun Jun 15 21:29:12 EDT 2008


In article 
<a0ff2569-a1a9-44c3-a68a-ee411dcd86eb at g16g2000pri.googlegroups.com>,
 takayuki <lawtonpaul at gmail.com> wrote:

> Hi,
> 
> I'm studying python via the exellent book "How to think like a python
> programmer" by Allen Downey.
> 
> Noob question follows...
> 
> animals.txt is a list of animals, each on a separate line: "aardvard,
> bat, cat, dog, elephant, fish, giraffe, horse, insect, jackelope"
> 
> I want to loop through the list of words and print words that don't
> have any "avoid" letter in them.
> 
> def hasnolet(avoid):
> 	fin = open('animals.txt')
> 	for line in fin:
> 		word = line.strip()
> 		for letter in avoid:
> 			if letter in word:
> 				break
> 			else:
> 				print word
> 
> hasnolet('abcd')
> 

I could give you a fish, or I could teach you to fish.  I'd rather do the 
latter.  So...

Take your inner loop:

>     for letter in avoid:
>        if letter in word:
>           break
>        else:
>           print word

and instrument it so you can see exactly what's happening.  Try something 
like:

>     for letter in avoid:
>        print "letter = %s" % letter
>        if letter in word:
>           print "it's in word"
>           break
>        else:
>           print "no it's not"
>           print word

and see if that helps.



More information about the Python-list mailing list