The return statement in a Python function

In this tutorial, we are going to learn about return statements in Python along with some examples.

Basically, when we call a function, to get the result of that function we use a return statement so the return statement returns the result or output of our function.

For example, we have to find the sum of two number

  1. I’m going to define a function with the name of addtwo.
  2. Def addtwo(a,b)- Here this addtwo function takes two values as an argument at the call time.
  3. Then I define a new variable “add” that stores the sum of these two numbers as shown in the code below in line 3.
  4. Then finally I want the output of this function when I call them so I use the return statement to get the result: return add.

 

# I'm going to define a addtwo function
def addtwo(a, b): #it will take 2 value a,b as an argument
    add = a + b
    return add

# Now I call this function
x=addtwo(4, 5)
# In line 7 "x" store the result of that function so basically here we assigned the return value of addtwo function which is "add" to "x"
# To show that value we have to use print function
print(x)

 

Output:

9

We can also return multiple values in Python as well

  1. This time we will find the sum and average of those two numbers a,b.
  2. To return multiple values we have to just separate those values with the comma(,)
# I'm going to define a addavg function
def addavg(a, b): #it will take 2 values a,b as an argument
    add = a + b
    avg=(a+b)/2
    return add,avg  # to return multiple values we have to just separate those value with the comma(,).

# This time this function return two value so we need two variables to assigned those two values.
# Now I call this function
x,y=addavg(4, 5)
# In line 7 "x" store the add and "y" store the avg 
print(x,y)

Result:

9 4.5

Thus, we have learned how to use return statements in the case of functions and also about the functions where we can return multiple values.

Leave a Reply

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