Essentials About Python Return Statements
photo credit:Rubaitul Azad, Unsplash
Introduction
This post will guide you step-by-step on Python return statement with indepth details and examples to give you a very clear picture on the concept of return statement in Python as well as the usage of the return statement. Using return statements needs a good understanding of the definition of the return statement that we will be learning soon in the following passages. Also, we will see as we start doing python projects, that, the skill in using the return statement, that is, when to use the return statement, how to use the return statement.
What Is A Return Statement
The keyword return is a Python in-built keyword that is used in python programs for evaluating expressions and conditions and returning something to the caller of the function. In other words, the python return statement is a statement that can be written inside a python function in order to send the required result to the caller of the function. The return statement is composed of the return keyword followed by an expression or value based on what the function wants to execute for the caller of the function.
The syntax of the return statement is written as
def function_somename(parameters):
#code block for function
return value
Why Are Return Statements Used
Return Statements in Python is used to return some value when we call a program. Obviously in every program that we run, we want to call the program to return something that is required by the caller, and also note that the return keyword is the in-built keyword in Python. The usage of the return keyword helps us in running a program efficiently, have a clear code while simultaneously improve the readability of the code block.
When the return statement is executed, the given function at that particular phase is terminated and the required value is returned to the caller of the function. As you can see in the above code syntax structure, the return statement can not be used outside the function.
Returning The Result Of Addition Of Numbers
In this case, we are going to see how the return sttement works for an add function where we are adding two numbers namely, a and b variables and then assigning the value of a+b to the result variable. Then we use the return statement by writing return result. You can see the code block as shown below in this example 1
In Example2, there is a slight difference how we use the return statement. Here we straightaway return num1 + num2 as a return statement where num1 and num2 are the parameters in the add function. You can compare both the example 1 and example 2 and decide to use the return statement in either of the ways as depicted in the two code blocks, Example 1 and Example 2 respectively.
Example 1
#def add(a,b):
#result = a+b
#return result
#output = add(16,7)
#print(f"output is {output}")
#output is 23
Example 2
def add(num1,num2):
return num1 + num2
result = add(10,70)
print(result)
#output: 80
Returning The Result For Subtraction Of Numbers
In this case, we refer to Example 3 where we consider two parameters num1 and num2 that are being subtracted and after defining the subtract function, we immediately return num1 + num2, as shown in the below example.
Example 3
def subtract(num1,num2):
return num1 - num2
result = subtract(10,70)
print(result)
#output: -60
Returning The Result For Multiplying Two Numbers
In this case also, we immediately use the return statement after defining the multiply function as shown below in Example 4.
def multiply(num1,num2):
return num1 * num2
result = multiply(10,70)
print(result)
#700
Returning Results For Conditional Loops
In this case, we first define the function that is being used to check the conditions and then inside the function, we use return statements after every condition, that is, first we consider the condition if num is greater than 0, and in that case we return 'positive' and then we check if the number is less than 0 in which case we return 'negative' and in the last condition that is if neither greater than zero or less than zero, then we use the return statement for returning 'zero' as shown below in the code block of Example 5.
Example 5
#def check(num):
#if num > 0:
#return "positive"
#elif num < 0:
#return "negative"
#else:
#return "zero"
#print(check(70))
#print(check(-55))
#print(check(0))
#positive
#negative
#zero
Return Results For Greeting A User
We first define the function for the welcome message with a parameter, name , to greet the name of the person or user. Then we use the return the statement for returning the value of the greeting message by using the f string in Python as shown below where the name parameter is mentioned in curly braces , that acts like a placeholder and when greeted, it will greet the person by that specific name that is stored or provided in the data. You can see in the output console, how the greeting message greets the user with her name that was provided inside the print statement. The full code block is in Example 6 as shown below.
Example 6
#def welcome_msg(name):
#return f"Hello, welcome to my coding world, {name}"
#print(welcome_msg("Emily Pooper"))
#output in console Hello, welcome to my coding world, Emily Pooper
Returning A Value For The Calculated Price
In this case we are going to return a value for the final price after calculating the price and discount. This example is a very simple one in which we first define the function for calculating the final price with two parameters, namely, price and discount. Then we write the formula for calculating the final price by calculating the discount from the price . Next we return the value for the final price by writing return final_price.
You may refer to the code block in Example 7 below to practise this return statement in such cases.
Example 7
#def calculate_final_price(price,discount):
#final_price = price -(price*discount/100)
#return final_price
#print(calculate_final_price(100,10))
#outcome 90.0
Returning The Value Of Division Of Two Numbers
In the below example 8, we define the divide function with the two parameters num1 and num2 and then we return the value of this division by writing return num1/num2. This is the easiest example/way to use a return statement in simple calculations.
Example 8
def divide(num1,num2):
return num1 / num2
result = divide(100,10)
print(result)
#output is 10
Returning A Simple Welcome Message.
In this case we define the welcome function with a parameter , called, msg and then we assign a value of "Hello World!" to the msg parameter. Next we just return msg. We will get to see the value of the welcome message in the output as shown below in Example 9.
Example 9
def welcome(msg):
msg = "Hello World!"
return msg
print(welcome('msg'))
#output: Hello World!
Returning Without Any Value
We observe that in Example 10, when we did not use the return statement in the same code block, we observe that the output in the console is showing the output as None. This is because we did not use the return statement there in example 10. So, now, we know the importance of using the return statement in order to get a resultant value or rather, in order to return the value of the operation that is being carried out in the function.
So, if we DON'T use a return statement in a function, then it returns the special value, None in the outcome. Also, if we use a return statement but without any value there, then also, we get the special value, None in the output, as shown in the code blocks below.
Hence, either if we don't use a return statement or if we use a return statement without any value mentioned, in both of the cases, the function will return the special value , None, as shown below. In the first case of example 10, the function did not even ask to return, then how to return any value and in the second case of the same example 10 as shown below in the code block, the function uses return keyword but nothing else after return. So the function will wonder, return WHAT ?? I hope, you understand what I am trying to say? I am trying to humanise the code block to make you understand more realistically.
Example 10
def welcome(msg):
msg = "Hello World!"
print(welcome('msg'))
#output: None as there is no return statement in this code block
def welcome(msg):
msg = "Hello World!"
return
print(welcome('msg'))
#output: None as return statement is without any value in this code block
Using Multiple Return Statements
In this case as shown in example 11, we return the specific value based on the conditions. In this example , if the remainder of a number n divided by 2 is zero, then we return the value of 'even' and if the remainder of the above division is not zero, as indicated by the else condition, then we return the value of 'odd'.
This is exactly like the way we communicate in our English language:
First we describe or define the function my_number carrying a parameter n, then, we use the return statements as stated above. This is quite easy to use if you understand what is happy in the if-else loop.
Hence, what we see here is that this python function uses multiple return statements, in this case, two return statements and in such a scenario, the return statement that fulfils the confition first will be the one to execute the function and then the function will exit at that point. That is, in this example 11, we see that there are two conditions , one if the remainder of the division is equal to zero and the other condition is if the remainder of the division is not equal to zero. Now, based on the code block below, the function is supposed to return 'even' if it fulfils the condition that the remainder of the number n divided by 2 is equal to 0, in other words, the remainder value is zero and if it fulfils the condition that the remainder of the number n divided by 2 is not zero, then, it has to return 'odd'. We have called the function for checking the number, 70, if it is even or odd. Next on calling the function for the number 70, it checks to see that the remainder of the division is zero, hence , the function returns 'even' in the output . The moment the function returns 'even' in the output, the function is terminated since the first condition of the function, that is, the n%2 == 0 is fulfilled, the first return statement is executed, and therefore, the function exits the program at this point and does not go further to execute the second following return statement in the function.
This is a very important point to remember while using multiple return statements in a function, that, only the return statement that fulfils the condition first, will get executed first and then terminate the function and will not execute the next return statements once the required one is already executed.
Example 11
def my_number(n):
if n%2 == 0:
return 'even'
else:
return 'odd'
result = my_number(70)
print(result)
#output: even
Returning Lists
As shown below in example 12, in the function given below in the code block, we write the return statement right after defining the function as shown below. We ask to return the value of the number raised to the power of 2 and 3 respectively. After writing the return statement, we create the variable, result to store the values of this calculation for the number, 4. The output will give you the value of 16 when you raise the number 4 to the power of 2 and it will give you the value of 64 when you raise the number 4 to the power of 3. The result that is returned as you can see from the output is actually a Python list , [16, 64]. This is because, we had the function to return the parameter, raised to the power of 2, that is a square of the number and also raised to the power of 3, that is cube of the number. Python lists store collection inside a square bracket as shown below in the output of this code block, for example 12.
Example 12
def myfunction(num):
return[num**2, num**3]
result = myfunction(4)
print(result)
#output : [16,64]
Returning Values For Counting Items
In the example 13 as provided below, we define the function my_pet_count() and then right below write the return statement by asking to return the value 2,4,7.
This is a very simple way of first defining a function and then asking to return some value, in the above function, we are asking to return the count of my pet , in my_pet_count function.
Example 13
def my_pet_count():
return 2,4,7
print(my_pet_count())
print(type(my_pet_count()))
#output: (2,4,7) <class 'tuple'>
def myfunction(name,age):
name = "Gigu"
age = 16
return name,age
print(myfunction('name','age'))
#output: ('Gigu', 16)
A Single Return Statement For Returning Multiple Values
In the above function myfunction(name,age) we define the function first and then initiate the value of name and age with values, "Gigu" and 16 respectively. Next, we ask to return the name and age by writing return name,age. Note the usage of comma in between the names of the parameters name and age. We call it returning multiple values, since, in the return statement, we ask to return both name and age both in one return statement! This renders the code to be faster and more efficient since you can write one return statement for return multiple items just in one line!
Using Return Statement For A Boolean Function
In the below example 14, in the first case for the is_true boolean function, we use the return statement to return the boolean number. Then we check if a specific number 4 is greater than 2 and since 4 is greater than 2, when we check if the is_true is True or False, in this case, we get the output in the console as True. Had we checked is_true for number 2 is greater than 4 or 2 > 4, then, we would have got False in the output console since 2 is obviously not greater than 4. So, here, we are using the return statement to return the boolean True or False for the checked specific use cases.
Returning A Function From A Function
In the below example15, you can see that function1 defines function2 that accepts the name parameter. When function1 is called with the name, "Helen", function1 returns function2, that was assigned to message. When message() is called, it returns "Hello, Helen"
This is how function1 returns the other function2.
Example 14 & 15
def is_true(num):
return bool(num)
result = is_true(4>2)
print(result)
#output : True
def function2():
return f"Hello, {name}"
return function2
#get the function returned by function1()
message = function1("Helen")
#call the returned function
print(message())
#output: Hello, Helen
Conclusion
We have learnt how to use return statements in Python for different use cases as explained in the above paragraphs. Hence as seen in the above examples, a return statement is used to end the execution of a function call and it returns the value of the expression after using the return keyword . Whatever statements are there after the return statement, are not executed. Also, when you do not use the return key word, then, the value of the expression is not executed and in the output, we get the special value , None. When you return statement without any expression, then also, it returns a special value, None in the output.
In all of the above examples, we have observed that the return statement is used to invoke a function in order to execute the passed statements.
The return statement helps the function to return something to the caller of the function, this something could be either a value, or an expression or another function. It is very important to remember that a return statement could only be used inside a function as observed in several of the example scenarios above in this post.
Also, before returning something to the caller, the program evaluates the expression that the return statement is carrying, before executing the function. In case of multiple return statements with multiple expressions, then, the return statement that fulfils the condition of the function first, will be the one to be executed and then it exits the program and does not further execute the next set of return statements.
Hence, as you have observed, once the return statement is executed, it terminates the execution of the function at that point itself. In other words, the function is terminated , once the particular return statement is executed. Sometimes, using single return statements, a function could return multiple values, the examples of which we have already seen above in the above paragraphs.
More for you to read on Python for Beginners:
Comments
Post a Comment