Understand Python Return Statement for Python Beginners – Python Tutorial

By | October 14, 2019

Python return statement is often used in python function. What does it mean? In this tutorial, we will introduce it for python beginners.

The syntax of python return

return [value]

The value is optional.

Why do we use return statement?

1.Use it to return a value for python function

This is the comman usage of return statement. For example,

def getValue():
    x = 1 + 1
    return x

In this function, we use return statement to return the value of x. It will be 2.

2.Use it to stop function to continue to run

This is another important feature of return statement, we can use it to stop a python function to run. Look at code below:

def printValue():
    for i in range(100):
        print(i)
        if i > 10:
            return
        
printValue()

In printValue() function, when i > 10 we will use return statement to stop to run this function. The result is:

0
1
2
3
4
5
6
7
8
9
10
11

However, you should notice the return statement used in python try, except and finally statement, the finally statement must be executed no matter return statement in try or except statement. You can read this tutorial to understand.

Understand Python Return Value in Python Try, Except and Finally for Beginners – Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *