0

Need help to understand code Can someone please answer why am getting none when I print hand

s='hellothisisawesomeharpreet'
newdic={}
for i in s:
    newdic[i]= newdic.get(i,0)+1

print newdic

def display_hand(newdic):
    for letter in newdic.keys():
        for j in range(newdic[letter]):
            print letter,

hand = display_hand(newdic)
print hand     
{'a': 2, 'e': 5, 'i': 2, 'h': 3, 'm': 1, 'l': 2, 'o': 2, 'p': 1, 's': 3, 
'r': 2, 't': 2, 'w': 1}
 a a e e e e e i i h h h m l l o o p s s s r r t t w None

1 Answers1

0

The problem is in this line:

hand = display_hand(newdic)

And this line:

print letter,

What happens is that display_hand() doesn't have a return statement.

If there is no return statement, the function will default to None. It doesn't care about if there is a print statement or not.

That's because printing in a function is, according to Python, like a side effect of the function, but not the result itself of it. Which, again, according to Python, is actually whatever that is returned.


So, in conclusion, change that line, from:

print letter,

To:

return letter,
Juan T
  • 1,219
  • 1
  • 10
  • 21
  • ohh yeah, thanks :) – Harpreet Singh Apr 09 '17 at 22:07
  • 2
    Well, if it's `return letter,` then it just returns the first letter, not all like you want. – fuzzything44 Apr 09 '17 at 22:11
  • Oh yes, I forgot about that, it is not as easy as changing the word `print` for `return` since it finishes the function. If you need it, Harpreet Singh, I'll edit my answer to fix that, for the time being, I'll leave it as an exercise. – Juan T Apr 09 '17 at 22:22