Python: What does “return” mean? Explained with 10 Examples!

In this article, let us learn about the “return” keyword in Python with the help of some examples.

The very fact that you have googled and found this article shows that you are a keen learner who thinks differently!

Keep it up and I am sure you will become a master craftsman in the world of Python in no time at all!

For those of you in a hurry, here is a short version of the answer.

The Short Version of the Answer

What is the meaning of the “return” keyword? The keyword “return” is used to exit functions, while “returning” any values to the calling function.

Consider the simple example below.

def calculate_area(length, breadth):
    area = length * breadth
    return area

# Usage of function
area = calculate_area(10, 5)
print ("Area of the rectangle = ", area)

Here the return statement is used to

  • exit the “calculate_area()” function and return the execution of code from Line-3 to Line-6, and
  • return the value in the variable “area” to the calling code at Line-6.

Don’t worry If you don’t understand what the above answer means, as this answer is aimed at people who just want to refresh their memories!

This article is specifically crafted keeping beginners in mind, so if you are feeling confused, forget that you ever read the paragraphs above, find a quiet place, focus for the next 10 to 15 minutes and read the rest of the article, then come back and read the answer above, I guarantee this will make more sense!

Let us start our journey by learning some fundamental concepts that are needed to understand the “return” keyword!

Fundamentals Needed Before You Can Understand The “return” Keyword

I have used the term “keyword” a lot above, but what does “keyword” mean?

Keywords are the “Building Blocks” of Python

The basic building block of any human language is words, the same is true for computer languages too!

Words are used to make sentences and sentences are used to get your idea across to the person you are communicating with.

Take a look at the words below.

words

Only the word “YES” can be found in an English dictionary, other words even though they make sense to us are not what is considered as “formal”.

This is because, while a native or a fluent English speaker might understand words like “aargh” not everyone will!

Our computers vocabulary is limited to just 2 words: 0 and 1.

Since we can’t write all our instructions to the computers in binary, we invented computer languages (like our “Python”)

Using computer languages

  • we can write our instructions in a way that is more comfortable for us,
  • then let a compiler translate that to 0’s and 1’s and
  • then eventually let the computer execute our instructions!

The vocabulary of such computer languages even though much larger than just 0 and 1, they are still nowhere near to that of humans.

The words in the vocabulary of computer languages are called tokens

These “tokens” are parsed (“parsed” is software slang for “understood”) one by one by Python as our code is executed.

These “tokens” can be classified into the following categories

  • Keywords
  • Identifiers
  • literals
  • operators and
  • delimiters

Similar to the way that we make sentences using words, in computer languages, the “tokens” above are used to make “statements“.

For example,

>>> a = 10

In the line above:

  • “a” is an identifier,
  • “=” is an operator, and
  • “10” is a integer literal

There are no keywords or delimiters in the line above but we will get to that in a second.

“Keywords” are tokens that are reserved for “special” uses and we cannot use them as variable names.

For example, we cannot use keywords like “if” like this

>>> if = 10
  File "<input>", line 1
    if = 10
       ^
SyntaxError: invalid syntax

The only way to use the word/token “if” and “else” in our Python program is to use them when we need to run some code conditionally as shown in the example below.

a = 10

if a == 10:
    print ("a is equal to 10")
else:
    print("a is not equal to 10")

Here the keywords “if”, “elif” and “else” are used to tell the python program that we want to do some condition checking and proceed to execute only select lines based on what the condition evaluates to.

A Challenge for you!

Before looking at the output, I want to challenge you to compute in your heads and predict what the code will print!

These thinking exercises will condition your brain to think like a programmer!

Are you ready? Okay, time for the explanation!

In the example above, since the value of “a” is equal to “10”, “if” gets executed and we get the following output

a is equal to 10

Here is a short intro to the “Python Interpreter” in case you are not familiar with it. If you are already familiar with the interpreter, how to launch and use it, you can safely skip this side-note!

Side-Note: A Short Intro to the “Python interpreter

The Python interpreter, simply put, is the command line prompt “>>>” you will get when you enter the “python3” command in your Linux or Mac terminal (“3” stands for Python version 3).

This way of using python is also called using the “Interactive mode of the Python Interpreter”

$ python3
Python 3.8.10 (default, Sep 28 2021, 16:10:42) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

If you are in windows, you can open up the interpreter app by opening the command prompt and by entering the following command

>python
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Here you can play around with any python program, one line at a time as shown below!

Python interpreter Example#1

You can even use this environment like a calculator by typing the expression to be evaluated as shown below!

Python interpreter as Calculator

I remember the first time I played around with the interpreter, it was loads of fun! To this day, it is still my go-to calculator app!

Go ahead, play a little with the interpreter! You can always bookmark this page and come back to it later!

Alright if you are done playing around with the interpreter let us go back to the main focus of this article, which is about learning the comparison operators.

Just to get the concept of “tokens” more clear let us take another example.

a = 10
b = [10, 0]

if a < 10:
  print("a is less than 10")
elif a == 10:
  print("a is equal to 10")
else:
  print("a is greater than 10")

The above program comprises of the following tokens.

Identifiersa, b (Variable identifiers)
print (built-in function identifier)
LiteralsInteger literals: 10, 0

String literals:
“a is less than 10”
“a is equal to 10”
“a is greater than 10”
Operators=, < , ==
Keywordsif, elif, else
Delimiters“[]”, “()”, “,”, “:”
Tokens in Example#5

Now that we have understood how computer languages work and how tokens are the vocabulary of computer languages, let us turn our attention to “keywords”

You can think of “keywords” as “words reserved for a specific uses”!

But then how do we know if a given token is a keyword or if we are allowed to use them as identifiers (variable names, function names, and class names) in Python?

Let us learn that next!

How to know if a given word is a keyword?

You can do this 2 ways

  • research on the internet (the hard way!)
  • use the keywords module in Python (the easy way!)

Let us see how we can use the keywords module to check if a given word is a keyword (Trust me this is very easy!)

You can do so on the python interpreter as shown below.

>>> import keyword
>>> keyword.iskeyword("apple")
False
>>> keyword.iskeyword("if")
True
>>> keyword.iskeyword("else")
True

As you can see “apple” is not a keyword but “if” and “else” are!

The keywords module also lets us see the full list of keywords using the following command

>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

As you can see there are 35 keywords here that are reserved for special purposes.

The next short section is a “fun” experiment. A word of warning the next section is meant for intermediate programmers and not beginners!

Side-note#2: A Fun Experiment

As we already know, print is an inbuilt function used to print some stuff on the screen. If you looked closely at the above list of 35 keywords, print is not one of them.

That is because print is an identifier and not a keyword.

So does this mean we can use that as a variable name in our code? What will happen if we do so?

Let us experiment and play with that!

>>> print("Hello Inventors!")
Hello Inventors!
>>> print = 10
>>> print
10
>>> print("Hello Inventors")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

In the example above

  • 1st we print “Hello Inventors” onto the screen using the “print” function
  • Then we use print as a variable name and assign the value to 10
  • Then we again try to print “Hello Inventors” again.

And the Python interpreter throws us an error saying you can’t do that!

So what happened there?

Have a look at the image below.

When we first called print function, the identifier print was pointing to the function that prints stuff

But as soon as the line “print = 10” got executed, the Python interpreter reassigns it to the integer value 10. Hence the error message “TypeError: ‘int’ object is not callable

Here ‘int’ stands for integer, hope you got the point!

This usage of using built-in functions as variables is considered extremely bad practice, so never do this!!

I hope you are already familiar with the concept of “functions”. If you are not feeling too confident about it then fear not! As I have written another article on functions that teaches all the tricks you need to know as a Python programmer to wield the full power of functions. You can find that in the link below.

Functions in Python: Explained Using 10 Examples!

So read that one and then come back here and continue with this one!

Now that we have understood the building blocks of the python programs and what the role of “keywords” are, let us go ahead and learn more about the return keyword!

What Does the Keyword “return” Do?

The keyword “return” is used in 2 specific scenarios. Let us see them one by one!

Using “return” to return values

This 1st scenario is where the return keyword is most often used. Have a look at the example below.

def calculate_area(length, breadth):
    area = length * breadth
    return area

# Usage of function
area = calculate_area(10, 5)
print ("Area of the rectangle = ", area)

Here

  • Line-6 is executed first (as this is the 1st line outside of any code blocks in our program)
  • Line-6 “calls” the function in line-1, which means the flow of execution of code goes from Line-6 to Line-1.
  • Then Lines 1, 2, and 3 are run by our computer.
  • When the computer reaches the “return” statement in Line-3 the computer exits the function and comes back to Line-6.

This is where the magic happens! The computer changes Line-6 from

area = calculate_area(10, 5)

to

area = 50

So how did this happen? When the return statement was executed by the computer, the value that came with the return statement replaces the “function call”!

In our case, the value that was returned was “area”, which is 50 (10 * 5 = 50), hence ” calculate_area(10, 5)” was replaced by “50” as shown above.

The diagram below explains how the computer executes the code

Example#9: Execution Flow
Example#9: Execution Flow

The output of this example is shown below.

Area of the rectangle =  50

Thus the return statement can be used to transfer values from one place to another place in our programs!

Using “return” to do an “early exit” and return to the calling code

Don’t worry if the above heading looks confusing, the concept is fairly simple and straightforward!

Consider the example below

def print_result(age):
    if (age > 0) and (age < 150):
        if age >= 18:
            print ("You can vote!")
        else:
            print ("You cannot vote!")   


def can_you_vote():
    retries_left = 3
    while (retries_left > 0):    
        age_str = input("Please enter your age: ");
        age = int(age_str)
    
        # if the age is valid, print result and return
        if (age > 0) and (age < 150):
            print_result(age)
            return
        else: # age is invalid, retry!
            retries_left -= 1;
    
    # too many wrong answers from the user
    print ("Retries Exhausted")

can_you_vote()

Problem Being Solved In This Example

The example tries to solve the following problem.

  • we want to make a program that will get the user’s age and prints out if the user does or doesn’t have the right to vote.
  • we want to do a sanity check to ensure that age entered is above 0 and below 150.
  • we want to ensure that the user gets a chance to correct any typing errors they might make while giving us their age. (maximum 3 chances)

Depending upon

  • which attempt the user gets the age right,
  • or if the user fails in all 3 attempts,

the execution flow can take 2 different paths.

Execution Path#1

In this path

  • We ask the user to enter their age,
  • then we do a sanity check to see if the entered number if valid. (any number greater than 0 and less than 150 is considered valid)
  • The check succeeds before the 3 attempts expire, we print out if the user has the right to vote or not.

This path is shown in the pic below.

I want you to focus on the “return” statement in this path, from where the function exits. Here the return path does not return any values, it just exits the current function and “returns” to the calling function.

Thus the return statement can also be used to choose an “execution path” without returning any values.

Example#10: Execution Path 1
Example#10: Execution Path 1

In the output below the user gets the age right in the very 1st attempt!

Please enter your age: 20
You can vote!

In the below output, the user gets the age right in the 3rd and final attempt!

Please enter your age: 200

Please enter your age: 500

Please enter your age: 33
You can vote!

(A keen reader might argue that the above output is not the same as path#1 and he/she would be right! But for the sake of keeping this example simple, we ignore how the code execution takes place inside the function)

Execution Path#2

The second path is when we have a naughty user who won’t tell us the real age! Once they get all 3 chances wrong we print out an error message! This path is shown in the picture below.

Example#10: Execution Path 2
Example#10: Execution Path 2

The output will look like the following.

Please enter your age: 0

Please enter your age: 300

Please enter your age: 400
Retries Exhausted

Here the point to note is that the function returns without a return statement!

We don’t need one unless we want to skip the execution of some statements and exit!

In this example we skipped the execution of the line “print (“Retries Exhausted”) ” with the help of the “return” keyword.

Where To Go From Here?

If you made it this far, then bravo to you! Great job!

I hope I did a good job quenching your thirst for knowledge about the “return” keyword!

With that, I will end this article.

Hope you had a good time reading this article and you have learned something useful!

Feel free to share this article with your friends and colleagues!

Also, check out the articles in the “Related articles” sections below!

Related articles

Python Comparison Operators Explained Using 10 Examples!

Python “is” and “is not”: Explained Using 8 Examples!

Python “in” and “not in”: Explained Using 8 Examples!

References

  1. Keywords Module in Python
  2. Lexical Analysis in Python
  3. Delimiters in Python
  4. How to identify keywords in Python

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn