0

I want to understand why does this function print "None" at the end, even if the dictionary has only 3 keys.

def groups(group_dictionary):
    
    i = 0
    for group in group_dictionary:
        print(group)
        print(i)
        i = i+1


print(groups({"local": ["admin", "userA"], "public":  ["admin", "userB"], "administrator": ["admin"]}))

Output:

local
0
public
1
administrator
2
None #I don't understand this line 

Thank you

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • The `question2answer` tag is only for a specific PHP framework. It has no place in a Python question. – Charles Duffy Sep 14 '21 at 16:54
  • 2
    Because your function return None – Abdul Niyas P M Sep 14 '21 at 16:55
  • The none value is not a key for the dictionary rather it is the value returned by the function "groups". A function without an explicit return value returns None is python. – the__hat_guy Sep 14 '21 at 16:56
  • Your function prints but doesn't return anything. If you try to print a function that doesn't return anything, `None` will be printed, because a function that doesn't return anything implicitly returns `None`. So, your function is running and printing your dictionary just fine - there are no `None` keys. It's just that you're unnecessarily trying to print the result of the `group()` function. – Random Davis Sep 14 '21 at 16:56
  • Every Python function returns `None` if you don't explicitly return a value. So `groups()` itself returns a value of `None` and `print(groups())` prints `None`. You can fix this by calling `groups` on its own and skipping the outer `print` function. – Matthias Fripp Sep 14 '21 at 16:57
  • @CharlesDuffy Thank you for the info, I didn't know. – Salah.Louizy Sep 14 '21 at 17:01
  • Thanks everyone, I got it now! – Salah.Louizy Sep 14 '21 at 17:04

1 Answers1

0

It is printing the return value of groups function, which is None (no return statement).

khachik
  • 28,112
  • 9
  • 59
  • 94