Print versus return in functions

It is not clear to me always if you have to use a PRINT command inside or outside of a function. If you just want to PRINT without any further calculations or use to save the variable, should you be always put it inside the function?

1 Like

Hi, welcome to the Forums!

Check this out:

Hello, @alexkuhlman427619655, and welcome to the forums.

Personally, I think it best if you don’t equate print and return at all.

  • print prints.
  • return returns.

Every function returns something. If we do not include an explicit return statement, None is returned in Python.

If you want a value to be printed, you use the print function, and pass the thing or things you want printed as an argument or arguments. Interestingly, the print function returns None.

print(print("Hi!")); #the nested print("Hi!") prints "Hi!" and returns `None`. The outer `print` prints the value returned by the nested `print`, so `None`

Output:

Hi!
None

2 Likes

Thanks. I think the confusion partly started with the following exercise that introduces strings such as commas and spaces within the return. From all previous exercises, these were always held within the print function. Why wrap that within the return?

def introduction(first_name, last_name):
   return last_name + ", " + first_name + " " + last_name
print(introduction("James", "Bond"))
print(introduction("Maya", "Angelou"))

In your example, you are returning an expression. An expression isn’t special. It’s still a value. The expression happens to be a string concatenation. The strings get concatenated into a single string, and returned to the caller. The caller happens to be the argument to a print function call, but each are still only performing their assigned tasks. return is returning, and print is printing. If the function itself didn’t return the string, it would be lost after the function finishes executing.

A common experience among new coders is something like this:

def introduction(first_name, last_name):
    print (last_name + ", " + first_name + " " + last_name) #print something
  #no explicit return, so None will be returned

print(introduction("James", "Bond")) #what gets printed?

Output:

Bond, James Bond
None

Then the question becomes why was None printed? Hopefully it’s obvious now. :wink:

By returning the string from the function rather than just printing it we can assign it to a variable for later use if we like.

def introduction(first_name, last_name):
    return last_name + ", " + first_name + " " + last_name #return the expression

bond = introduction("James", "Bond")
angelou = introduction("Maya", "Angelou")

print(f"Hello, I'm {bond}. Who are you?\nI'm {angelou}.")

Output:

Hello, I’m Bond, James Bond. Who are you?
I’m Angelou, Maya Angelou.

3 Likes