In this post we will learn about return statement in python. It is used in the end of the code to return the result.
Introduction
Return statement is used to call the result in python program. Generally return statement will exit the function and return the value.
- Whenever return statement is used in function it will exit the function, the function will halt immediately and return the value to caller.
- This Return statement can return any value, object or datatype, numbers, lists, tuples, etc.
- Return statement in python can return multiple value.
- Function always does not have return statements.
- How to Return Multiple Values in Python.
Let’s see some examples:
def calculate(): x=int(input("Enter: ")) y=int(input("Enter: ")) sum=x + y diff=x - y return sum, diff result1, result2 = calculate() print(result1, result2)
Output:
Enter: 5 Enter: 6 11 -1
In the above code calculate is function name in first line we are declaring the function. the followed lines are statement that takes input values from user and calculates the values.
In sixth line we used return statement which will return our results.
The following line will call the function to return the values.
Let’s see another example:
def user_input(): name = input("Enter your name: ") email = input("Enter your email: ") return name, email user_name, user_email = user_input() print("Hello, ", user_name) print("Your email, ",user_email)
Output:
Enter your name: john Enter your email: [email protected] hi, john your email, [email protected]
We cannot use return statement outside the function.
We should always call the function to execute our return statement.
Python return statement can return multiple value using objects, tuples, dictionaries, etc,.
Return statement can return a function within function also.