Posted by Marta on December 18, 2020 Viewed 1220 times
In this article, I will explain the use of return in Python and how to use return in python, including examples to help you get a better and more in-depth understanding of this concept.
The return keyword is essential in python and most programming languages, such as java, ruby, c++, etc.
The return concept is related to functions. A function is a set of instructions that perform a specific task labelled with a name. This way, you can call your function over and over, without repeating code. Your function will return the result of a calculation using the return python word.
For instance, let’s say that you write a function to check if a credit card number is valid. To do so, you could use the Luhn Formula. Here are the operations you need to perform sequentially to determine if a card number is valid:
The code below illustrates how to implement these steps in python:
def verify_credit_card(card_number): # Drop the last digit from the number last_digit = int(card_number[-1]) result_step1 = card_number[:-1] # Reverse the numbers result_step2 = result_step1[::-1] # Multiply the digits in odd positions (1, 3, 5, etc.) by 2 # And subtract 9 to all any result higher than 9 result_step3 = '' for digit in result_step2: doubled_digit = int(digit)*2 if(doubled_digit > 9): doubled_digit = doubled_digit-9 result_step3 = result_step3 + str(doubled_digit) # Add all the numbers together result_step4 =0 for digit in result_step3: result_step4 = result_step4 + int(digit) # Check if the result of module 10 is equal to the last digit, # if so, the card number is a valid number final_result = result_step4 % 10 return final_result == last_digit
This function uses the return term at line 29 to return a variable containing a boolean value, which indicates if the card number is valid or not. This way, you can assign the calculation result into a variable. Check out the following code:
is_card1_valid = verify_credit_card('4539797671535063') # Invalid number is_card2_valid = verify_credit_card('4929817131531581') # Valid number print(is_card1_valid) print(is_card2_valid)
The return keyword allows you to pass the function result to the piece of caller code. Any variable within the function will disappear or be wiped out from the memory once the function finished its execution. The only part remaining is the value the function passed back using the return statement. See the code example below:
def function(): variable1 = 2 variable2 = variable1*3 return 4 result = function() print(result)
The function above will return the value 4, and the variable1 and variable2 values will disappear as soon as the function is finished executing and can’t be accessed. In other words, variable1 and variable2 are only accessible in the function scope, which goes from line 1 to line 4. The only variable that is accessible outside the function scope is the variable passed back using return.
Additionally, the return statement indicates to the program to finish the execution and return the value that goes right after the return. See the code example below:
def function2(parameter1): if parameter1>5: return 1 return 2 variable1 = function2(6) variable2 = function2(3) print(variable1) print(variable2)
This function will return two different values and exit at two other places. The first time the function gets called since the parameter is greater than five; the program will exit the function at line 3, returning 3. The program won’t execute line 4. However, next time the function gets called using parameter1=3, the program will exit at line 4, returning 2. As soon as the program finds a return statement, it will leave the function and pass the specified value.
So far, I have covered the use of return in programming and how to return a single value; however, there are more possibilities. The python return allows you to return multiple values as well. You only need to separate each value by a comma. All values will be returned in a tuple, which you can access by index. See below an example of a function that return multiple values:
def function3(): var1 = 'value1' var2 = 'value2' var3 = 'value3' return var1, var2, var3 tuple_var = function3() print(tuple_var) print(type(tuple_var))
('value1', 'value2', 'value3') <class 'tuple'>
The function above will return three values wrapped in a tuple. Another option is using unpacking. This way, you can assign each value to a different variable. See the example below:
def function3(): var1 = 'value1' var2 = 'value2' var3 = 'value3' return var1, var2, var3 v1, v2, v3 = function3() print(v1) print(v2) print(v3)
value1 value2 value3
What if you like to return just two values? No problem, the return statement in python allows you to passed back any number of values you prefer. If you would like to give two values, you only need to add the return term and the two values to return separated by a comma. See the example below:
def function_two_values(): var1 = 'value1' var2 = 'value2' return var1, var2 value1, value2 = function_two_values() print(value1) print(value2)
You can use the return statement to return any value, including a collection such as a list. To pass a list from a function you need to add the return term followed by the python list. See a simple example below:
def function4(): list = [1,2,3,4] return list result = function4() print(result) print(type(result))
[1, 2, 3, 4] <class 'list'>
The function above returns a list of numbers. At line 5, I have assigned the result of executing the function, the list, to the variable output
result. Therefore the variable output contains the list. And last I have printed the outcome to make sure the code works as I expect.
What is the difference between return and print? When should you use return or print? These two statements can be confusing the first time you encounter them. The Print statement displays something on the screen to see the value of a variable is what you expect. Return won’t print anything on the screen. You can use the return to pass back a value from a function. Here is an example that illustrates this difference:
def display_sum(num1,num2): total_sum = num1 + num2 print(total_sum) result = display_sum(2,2) print(result)
The above function is not using return, only printing. Therefore the total is printed on the screen; however, the value is not passed back to the caller code. That’s why the result variable is None. Let’s see an example using return to see the difference:
def display_sum2(num1,num2): total_sum = num1 + num2 print(total_sum) return total_sum # New line result = display_sum2(2,2) print(result)
The function above is nearly the same as the previous one; it also prints the total. However, I have added a return statement. Doing so means the value saved in
total_sum is passed back to the caller function at line 6, and assigned to the
To summarise, this article covers the use of return in programming with examples and how to return multiple values using the return statement. Plus, the difference between using return and print. I hope you enjoy the tutorial, and thank you so much for reading and supporting this blog! 🙂
Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications
Unique lay-out and teaching programming style helping new concepts stick in your memory
Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples
Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.
Excellent read for anyone who already know how to program and want to learn Best Practices
Perfect book for anyone transitioning into the mid/mid-senior developer level
Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java