When working with Python, there are many functions which seem similar but should be used for different cases.

One such example is the use of the print() function and a return statement.

Basically, the difference between print and return in Python is that print prints text to the terminal and return returns data from a function.

These two concepts can be a little tricky to understand when learning Python so hopefully this article will be useful for you to understand the difference between print() and return in Python.

Using print() in Python to Print Text to the Terminal

The Python print() function prints text to the terminal. print() can be useful if you want to see the value of certain variables and can also be used if you want to communicate different messages to the user of the program.

You can use print() in a variety of ways but the most common is to use it and print a variable to the terminal.

Below is a simple example of how you can use print() in Python.

a = "hello"

print(a)

#Output:
hello

You can use print() to print multiple variables to the terminal window.

Below is an example showing you how to use print() to print multiple variables to the terminal in Python.

x = 0
y = 1
z = 2

print(x,y,z)

#Output:
0 1 2

Using return to Return Data from Function in Python

In Python, you use return in functions to return data from a particular function.

The most basic use of return is if you want to return a value from a function. For example, if we have a simple function which adds two numbers together, you can return the sum with return.

Below is an example showing you how to use return in Python. Note here that nothing is printed to the terminal unless you use print().

def sum_two(x,y):
    return x + y

sum_two(10,3)

#Output:

Note here that nothing is printed to the terminal unless you use print().

def sum_two(x,y):
    return x + y

print(sum_two(10,3))

#Output:
13

You can also use return to break out of functions.

Functions terminate when we return a value back, and so to break out of a function in Python, we can use the return statement. In this case, we will return nothing.

Below is an example of how to get out of a function early with a return statement.

def doStuff():
    print("Here before the return")
    return
    print("This won't print")

doStuff()

#Output:
Here before the return

Hopefully this article has been useful for you to learn the difference between print() and return in Python.

Categorized in:

Python,

Last Update: March 11, 2024