⊗pyPmUFRt 200 of 208 menu

The return statement in Python

Let's say we have a function that prints the square of the passed number:

def func(num): print(num ** 2)

If you don't need to display the value immediately on the screen, you can write it to some variable beforehand:

res = func(3) # the variable res now has 9

For this purpose, Python has a special instruction return, which allows you to specify the value that the function returns. The word returns means the value that will be written to the variable if it is assigned the called function.

Let's rewrite our function so that it doesn't output the result to the console, but returns it to a variable:

def func(num): return num ** 2

Now let's write the result of the function into a variable:

res = func(3)

Once the data has been written to a variable, it can be displayed on the screen, for example:

res = func(3) print(res) # 9

Or you can first change this data and then display it on the screen:

res = func(3) res = res + 1 print(res) # 10

You can immediately perform some actions with the result of the function before writing it to a variable:

res = func(3) + 1 print(res) # 10

We can call our function multiple times for different numbers and add up the results:

res = func(2) + func(3) print(res) # 13

To shorten the written code, you can call the function immediately by passing it to the print parameter:

print(func(3))

Make a function that takes a number as a parameter and returns the cube of that number. Use this function to find the cube of 3 and store it in the variable res.

Using the function you created, find the sum of the cubes of 2 and 3 and write it to the variable res.

byenru