Print a function with a print statement in it

Hi guys,

I have the a problem to understand how “print” in Python works exactly. Her ist a example:

def function(a):
     a += 1
     print a

In this situation the output is:

>>2
>>None

But shouldn´t be here a error if I print something in a function and then I print the same thing

again? Or shouldn’t this situation cause a “double print”?

Thank you for your help

Cheers

Maxim

Hello!
When you write print(function(1)), you are actually doing two things:
calling the function with a parameter of 1, and printing the result. So, when you call function(1), it adds 1 to the argument (in this case 1), and prints the result, so it prints 2. Then, you attempt to print the return value of the function, but since there isn’t a return value, it prints None.


If you had’ve done this:

def function(a):
   a += 1
   print(a)
   return a
print(function(1))

The output would be:

>>2
>>2

Since the function also returns a value (2).
I hope this helps!


Aside, see this post to format your code correctly.

3 Likes