Why do we use "return" statements in Python functions?
Published on Aug. 22, 2023, 12:20 p.m.
We use “return” statements in Python functions to signify the end of the function and to send a value back to the function call in the main program. When a function returns a value, we can use that value in the main program, assign it to a variable, or pass it as an argument to another function.
The “return” statement can be used with or without a value, depending on whether the function returns a result or not. If the function does not return a result, then the “return” statement can still be used to exit the function and return control to the main program.
Using “return” statements in functions is an essential feature of the Python programming language, and it enables us to build complex systems by breaking them down into smaller, manageable parts. By returning values and using those values in subsequent function calls, you can create a vast network of interconnected functions that work together to accomplish a more significant task.
here is an example of how to use “return” statement in Python:
def add_numbers(x, y):
result = x + y
return result
sum = add_numbers(5, 3)
print(sum)
In the above example, we define a function called “add_numbers” that takes two arguments “x” and “y.” Inside the function, we add the two arguments together and store the result in a variable called “result.” Then, we use the “return” statement to return the value of “result” to the main program. In the main program, we call the “add_numbers” function and store the returned value in a variable called “sum.” Finally, we print the value of “sum,” which is 8.
Alternatively, if you do not want to use the “return” statement, you can use global variables to store the result of a function and access it from the main program. However, this is generally not considered good programming practice because it can lead to naming conflicts and make it harder to maintain the code. Here’s an example of how you might use global variables instead of “return” statements:
result = 0
def add_numbers(x, y):
global result
result = x + y
add_numbers(5, 3)
print(result)
In this example, we define a global variable called “result” and then define a function called “add_numbers” that adds two arguments together and sets the value of the “result” variable to the sum. In the main program, we call the “add_numbers” function and then print the value of the “result” variable. Note that we need to use the “global” keyword inside the function to access the global “result” variable.