Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why do I get "none"
#1
Hello!

I tried this code
print(print('Hello'))

and here's what I got
Hello
None

Why do I get "none" displayed?
Reply
#2
Short answer: You get none because you asked it. But this is not very useful information :-)

With outside print() you're asking Python to print the value returned by the inside print() function. Since print function prints and don't have return part then None is returned by default. The None is the return value of the all functions which don't return (or yield) anything.

>>> def test():
...     pass
...
>>> print(test())
None
>>> def why():
...     print('Why?')
...
>>> print(why())
Why?
None
It's good practice to write functions which always return something explicitly and then print it if needed:

>>> def why():
...     return "Why?"
...
>>> print(why())
Why?
>>> print(f"{why()} It doesn't make sense.")
Why? It doesn't make sense.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
All python functions return None by default, even if not told to do so:
def hiccup():
    print('I do not specifically return None')

x = hiccup()
print(x)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020