How to Return a Value from a Function in Python?

Estimated read time 2 min read

In Python, you can return a value from a function using the return statement. The return statement is used to specify the value that should be returned when the function is called. Here’s an example:

def add_numbers(a, b):
    result = a + b
    return result

sum_result = add_numbers(2, 3)
print(sum_result)  # Output: 5

In this example, the add_numbers() function takes two arguments a and b, calculates their sum, and assigns it to the result variable. The return statement then specifies that the value of result should be returned as the result of the function.

When the function is called with the arguments 2 and 3, the sum of 2 and 3 is calculated and returned. The returned value is stored in the sum_result variable, which is then printed, resulting in the output 5.

You can return any valid Python expression as the return value, including variables, literals, or even other function calls. The returned value can be stored in a variable, used in further computations, or printed as needed.

Remember that when the return statement is encountered, it immediately exits the function, and any code after the return statement within the same block is not executed. Therefore, it’s important to ensure that the desired result is calculated and returned before reaching the end of the function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply