+ 2

Why does a function print None

In the example: def func(): print("Hi") var = func() print(var) The output is: Hi None I understand why the 'Hi' gets printed. It's being called from the function I defined. I do not understand why the None gets printed as well. Is that due to the function not having any arguments?

29th Oct 2018, 5:41 PM
Kashyap Zaveri
Kashyap Zaveri - avatar
9 Antworten
+ 5
A hint: https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2287/ edit: (this is an in-app link, not for browsers)
29th Oct 2018, 6:32 PM
Kirk Schafer
Kirk Schafer - avatar
+ 3
Kashyap Zaveri no, it runs like this <line 3> func() # print("Hi"), return None var = None <line 4> print(None)
31st Oct 2018, 12:58 AM
Flandre Scarlet
Flandre Scarlet - avatar
+ 2
because nothing is returned by func()
30th Oct 2018, 4:08 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 2
Kashyap Zaveri Thanks for letting me know; I'll have to mark those as in-app (not browser) links in the future.
31st Oct 2018, 2:50 AM
Kirk Schafer
Kirk Schafer - avatar
+ 2
Kashyap Zaveri Don't change anything, but try a negative number :)
2nd Nov 2018, 4:21 PM
Kirk Schafer
Kirk Schafer - avatar
0
Kirk - thanks for your reply but the link doesn't work for me. Flandre - The print(var) returns Hi, so shouldn't the func() output be above the Hi instead of below?
30th Oct 2018, 6:04 PM
Kashyap Zaveri
Kashyap Zaveri - avatar
0
Kashyap Zaveri print(var) prints Hi - does not returns. func() returns nothing(none), it only prints Hi. Seems you are using web version.
30th Oct 2018, 8:11 PM
Roneel
Roneel - avatar
0
Kirk - thanks for the tip on the app and the help. I rewrote it this way and it makes more sense to me: def func(a): print("Hi") if a >= 0: #this could have been any if statement return a var = func(5) print(var) If comment out the print statement I get only the "Hi". If I leave it in I get "Hi"\n5. Now the none makes sense since None type is used within the function arguments. I need to play around more to understand functions. But it seems I get output when I assign the function to a variable. It's the print(var) that gives the output of the function argument.
1st Nov 2018, 8:15 PM
Kashyap Zaveri
Kashyap Zaveri - avatar
0
Kirk, I ran the program with a negative and got None type. So then I rewrote it like this def func(a) print("Hi") if a >= 0: return a else: print("Error") var = func(-1) print(var) This time I get: Hi error None To me it seems if the condition isn't met then it must output something to let you know the condition isn't met. Since there is no argument in the original problem the condition to have an argument isn't met and it tells you the type is None.
5th Nov 2018, 8:31 PM
Kashyap Zaveri
Kashyap Zaveri - avatar