+ 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?
9 odpowiedzi
+ 5
A hint:
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2287/
edit: (this is an in-app link, not for browsers)
+ 3
Kashyap Zaveri no, it runs like this
<line 3>
func() # print("Hi"), return None
var = None
<line 4>
print(None)
+ 2
because nothing is returned by func()
+ 2
Kashyap Zaveri Thanks for letting me know; I'll have to mark those as in-app (not browser) links in the future.
+ 2
Kashyap Zaveri Don't change anything, but try a negative number :)
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?
0
Kashyap Zaveri print(var) prints Hi - does not returns.
func() returns nothing(none), it only prints Hi.
Seems you are using web version.
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.
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.