3

I have defined this function that takes a word and a string of required letters and that returns True if the word uses all the required letters at least once. When I run this, it gives me the correct output but I do not understand why it also outputs 'None'.

Here is my code:

 def uses_all(word, allused):
    boolean = False
    for e in allused:
        if e in word:
            boolean = True
        else:
            boolean = False
            break 
    print boolean 

print uses_all('facebook', 'd')

Output:

False
None

Comments on where I have gone wrong will be appreciated.

Hummus
  • 365
  • 1
  • 7
  • 16
  • 5
    `boolean` is a bad name for a variable -- it tells us the type of the variable, which we already know, since it's either `True` or `False`, but you're not telling us what it *means*. – Andrew Jaffe Sep 17 '12 at 20:00

3 Answers3

7

Your program prints boolean, which is False, so you know where that comes from.

If a function doesn't return anything explicitly, it automatically returns None, and when you use

print uses_all('facebook', 'd')

you're asking it to print what uses_all returns, which is None. Hence:

False
None

BTW, I think your function could be more concisely written as

def uses_all(word, allused):
    return all(e in word for e in allused)

Could make it more efficient, but that should be good enough for government work. The all function is really handy (see also any).

DSM
  • 342,061
  • 65
  • 592
  • 494
5

Because uses_all() doesn't have a return statement. If you return a value from the function, it will be printed instead of None, unless of course you return None :)

AJ.
  • 27,586
  • 18
  • 84
  • 94
0

You print the result of the function, but the function doesn't return anything (--> None)

If you want the result to be False False, add return boolean in the function.

Alternatively, if a single False is enough, you could change print uses_all('facebook', 'd') to just uses_all('facebook', 'd')

Junuxx
  • 14,011
  • 5
  • 41
  • 71