[Tutor] help with loop that is to be fed out of a word list

Alan Gauld alan.gauld at btinternet.com
Tue Feb 10 11:39:30 CET 2009


"David" <ldl08 at gmx.net> wrote

> def uses_all(word, required):
>    for letter in required:
>        if letter not in word:
>            return False
>    return True
>
> Now, I want to feed this code a list of words. This is what I have 
> so far:
>
>
> def uses_all(required):

It is usually better to leave things that work alone.
You could have renamed the original finction then used it
in your new one. That would make the code much simpler.


>    fin = open('words.txt')
>    for line in fin:
>        word = line.strip()
          if old_uses_all(word, required)
              print word

But as ever its better to return a value from a function rather
than print from inside so i'd make your new function:

def uses_all(required, wordfile="wordlist.txt"):
    words = []
    for line in open(wordfile):
        word = line.strip()
        if old_uses_all(word, required)
           words.append(word)
    return words

required = raw_input("what letters have to be used? ")
print required

for word in uses_all(required)
      print word

> The code runs, but does not print the words. All I get it the output 
> of
> the 'print required' command:

> I realise that my loop fails to execute beyond the first word in the
> list ("aa"), but why?

Look at your code:

> def uses_all(required):
>    fin = open('words.txt')
>    for line in fin:
>        word = line.strip()
>        for letter in required:
>            if letter not in word:
>                # print "False!"
>                return False

return exits the function so the first letter you find that is not in
a word you will exit.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list