Skip to main content

How to Print Function Output in Python

Printing Function Output: The Basics

To print the output of a function, you must do thre things:

  1. return a value from the function: Use the return statement to specify what the function should output.
  2. Call the function and capture the result: Assign the result of calling the function to a variable.
  3. Print the stored result: Print the returned result.
def example(name):
return 'site: ' + name # return statement is crucial

result = example('tutorialreference.com') # Call the function, store result
print(result) # Output: site: tutorialreference.com
  • The return statement is essential. Without it, the function will implicitly return None.
  • The function needs to be called, and the result must be stored in a variable and printed.

Common Mistakes Leading to None Output

If you're seeing None printed instead of your expected output, it's usually due to one of these issues:

Missing return Statement

If a function doesn't have an explicit return statement, it implicitly returns None:

def example(name):
print('site: ' + name) # Prints, but doesn't return anything

result = example('tutorialreference')
print(result) # Output: None
  • The output is None, because the function doesn't return anything.
  • Solution: Add a return statement to the function.

Assigning print() to a Variable

The print() function itself returns None. Never assign the result of print() to a variable if you intend to use that variable later:

website = print('tutorialreference.com')  # WRONG!
print(website) # Output: None

Solution: Store the value you want to print in a variable, then print the variable:

website = 'tutorialreference.com'
print(website) # Correct. Prints: tutorialreference.com

Functions with Conditional Returns

If a function has a return statement inside an if block (or any conditional block), make sure all possible execution paths return a value:

def get_name(a):
if len(a) < 5:
return a
# Missing return statement here!

result = get_name('tutorialreference.com')
print(result) # Output: None

Solution: Add an explicit return statement (or raise an exception) in the else case, or after the conditional blocks, to handle cases where the initial condition isn't met:

def get_name(a):
if len(a) < 5:
return a
return '' # Or raise an exception, or return a default value

In-Place Modification Methods

Many built-in methods that modify objects in-place (like list.sort(), list.append(), list.extend(), list.reverse(), dict.update(), etc.) return None. Don't assign the result of these methods to a variable:

a_list = ['tutorial', 'reference', 'com']
result = a_list.sort() # WRONG! sort() modifies in place
print(result) # Output: None

Solution: Call the method on the object, then print the (modified) object:

a_list = ['tutorial', 'reference', 'com']
a_list.sort() # Sorts in-place
print(a_list) # Output: ['tutorial', 'com', 'reference']