Print the output of a function in Python


Borislav Hadzhiev

Last updated: Sep 8, 2022


Photo from Unsplash

Print the output of a function in Python #

To print the output of a function:

  1. Make sure to return a value from the function.
  2. Call the function and store the result in a variable.
  3. Use the print() function to print the result.
def greet(name): return 'hey ' + name result = greet('bobbyhadz') print(result) # 👉️ 'hey bobbyhadz'

Notice that the function uses a return statement to return a value.

This is necessary because all functions that don't explicitly return a value implicitly return None in Python.
# 👇️ this function prints a message and returns None def greet(name): print('hey' + name) result = greet('bobbyhadz') print(result) # 👉️ None

The function in the example doesn't use the return statement, so it implicitly returns None.

The print function takes one or more objects and prints them to sys.stdout.

Note that the print() function returns None, so don't try to store the result of calling print in a variable.
website = print('') print(website) # 👉️ None

Instead, store the value in a variable and pass the variable to the print() function.
website = '' print(website) # 👉️

To print the output of a function, you have to call the function, store the result in a variable and print the result.
def do_math(a, b): return a + b result = do_math(12, 13) print(result) # 👉️ 25

If you are getting a None value when printing the output of the function, the most common sources of None values are:

  1. Having a function that doesn't return anything (returns None implicitly).
  2. Explicitly setting a variable to None.
  3. Assigning a variable to the result of calling a built-in function that doesn't return anything.
  4. Having a function that only returns a value if a certain condition is met.

Make sure to return a value in every branch of your function.
def get_name(a): if len(a) < 5: return a result = get_name('') print(result) # 👉️ None

The if statement in the function only runs if the provided argument has a length of less than 5.

In all other cases, the function doesn't return anything and ends up implicitly returning None.

To get around this, we can return a default value if the condition is not met, e.g. an empty string, 0, or any other value that suits your use case.
def get_name(a): if len(a) < 5: return a return '' # 👈️ return empty string if condition is not met result = get_name('') print(result) # 👉️ ''

Now the function is guaranteed to return a value regardless if the condition is met.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.