What is a Return Value?
In Python, the return
statement allows a function to send a value back to the caller. Think of it as a vending machine —you put in money, press a button, and it returns a snack!
Why Use return
?
- Gets a result from a function
- Allows further computation
- Stores the output for later use
Basic return
Example
A function that adds two numbers and returns the result.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Outputs: 8
The function computes a value and hands it back!
Using return
in Real Life
A function that calculates the price after tax.
def calculate_total(price, tax):
return price + (price * tax)
bill = calculate_total(100, 0.1)
print(f"Total bill: ${bill}")
Multiple Return Values
A function can return multiple values as a tuple!
def get_user_info():
name = "Alice"
age = 25
return name, age # Returns a tuple ("Alice", 25)
user = get_user_info()
print(user) # Outputs: ('Alice', 25)
Returning Early with return
A function stops execution as soon as it hits return
.
def check_even(number):
if number % 2 == 0:
return "Even"
return "Odd"
print(check_even(10)) # Outputs: Even
print(check_even(7)) # Outputs: Odd
Summary
Concept | Description |
---|---|
return |
Sends a value from a function back to the caller |
Multiple Returns | Returns multiple values as a tuple |
Early Return | Exits a function immediately |
Now you know how to return values like a pro in Python!
0 Comments