Python Return Values
Learn how Python functions send results back to the code
that called them using the powerful return
statement.
What You'll Learn
- Understand how the
returnstatement works. - Understand the difference between
print()andreturn. - Store returned values in variables.
- Use returned values in calculations and conditions.
- Return expressions and multiple values.
- Understand early returns and conditional returns.
- Work with functions that return
None. - Build practical programs using reusable return-based functions.
What Is return?
The return statement sends a value from a
function back to the code that called the function.
This allows a function to perform some processing and give the result back to the rest of the program.
def add(a, b):
return a + b
result = add(10, 20)
print(result)
30
The function calculates a + b and returns the
result to the caller.
A function can receive data through parameters, process
that data, and send a result back using
return.
print() vs return
One of the most important concepts for beginners is
understanding the difference between print()
and return.
print()
print() displays something on the screen.
def add(a, b):
print(a + b)
result = add(10, 20)
print(result)
30 None
The function printed 30, but it did not return
that value. Therefore, result receives
None.
return
def add(a, b):
return a + b
result = add(10, 20)
print(result)
30
Remember
print() → displays a value.
return → sends a value back to the caller.
Basic Return Values
A function can return numbers, strings, Boolean values, lists, dictionaries, and many other Python objects.
Returning a number
def get_score():
return 95
score = get_score()
print(score)
Returning a string
def get_message():
return "Welcome to PyLearn"
message = get_message()
print(message)
Returning a Boolean
def is_adult(age):
return age >= 18
print(is_adult(25))
True
Storing Returned Values
A returned value can be stored in a variable.
def multiply(a, b):
return a * b
product = multiply(8, 5)
print(product)
40
Once stored, the returned value can be used anywhere the variable can be used.
def multiply(a, b):
return a * b
product = multiply(8, 5)
print(product)
print(product + 10)
print(product * 2)
40 50 80
Using Returned Values
Returned values can be used directly in calculations, conditions, assignments, and other function calls.
Using a return value in a calculation
def square(number):
return number * number
result = square(6) + 10
print(result)
46
Using a return value in a condition
def is_even(number):
return number % 2 == 0
if is_even(10):
print("The number is even.")
The number is even.
Returning Expressions
You do not need to create a separate variable before returning a result.
def calculate_area(length, width):
return length * width
The expression length * width is evaluated and
its result is returned.
You can also use more complex expressions.
def calculate_final_price(price, discount):
return price - (price * discount / 100)
Returning Multiple Values
Python allows a function to appear to return multiple values.
In reality, Python packages the returned values into a tuple.
def calculate(a, b):
total = a + b
difference = a - b
return total, difference
result = calculate(20, 5)
print(result)
(25, 15)
The returned object is a tuple containing two values.
Important Concept
return a, b is effectively returning a
tuple containing a and b.
Unpacking Returned Values
Because multiple returned values are packaged into a tuple, you can unpack them into separate variables.
def calculate(a, b):
return a + b, a - b
total, difference = calculate(20, 5)
print(total)
print(difference)
25 15
This is a clean and useful Python pattern when a function needs to provide several related results.
Early return
A return statement immediately ends the
execution of the current function.
def check_number(number):
if number < 0:
return "Negative"
return "Positive or Zero"
print(check_number(-5))
print(check_number(10))
Negative Positive or Zero
When number < 0 is true, the function returns
immediately. The code after that return is not executed for
that call.
Once Python executes return, the function
stops immediately.
Conditional Return Values
Functions can return different values depending on conditions.
def calculate_grade(score):
if score >= 80:
return "A"
elif score >= 70:
return "B"
elif score >= 60:
return "C"
elif score >= 50:
return "D"
else:
return "F"
print(calculate_grade(88))
print(calculate_grade(72))
print(calculate_grade(45))
A B F
Each execution follows the appropriate condition and returns a result.
Functions Without return
A function does not have to contain a return
statement.
def greet():
print("Hello!")
result = greet()
print(result)
Hello! None
If a function finishes without executing a return statement,
Python automatically returns None.
Returning None
You can explicitly return None when a function
needs to indicate that there is no meaningful result.
def find_user(users, username):
for user in users:
if user == username:
return user
return None
users = ["Ali", "Sara", "Ahmed"]
result = find_user(users, "Bilal")
print(result)
None
Returning None clearly communicates that the
requested item was not found.
Many Python functions use None to represent
the absence of a result.
return with Loops
A return statement can be used inside a loop to immediately finish the entire function.
def find_number(numbers, target):
for number in numbers:
if number == target:
return True
return False
numbers = [10, 20, 30, 40]
print(find_number(numbers, 30))
print(find_number(numbers, 50))
True False
When the target is found, return True ends both
the loop and the function.
return vs break
break exits the current loop.
return exits the entire function.
Functions Calling Other Functions
One function can call another function and use the value it returns.
def calculate_subtotal(price, quantity):
return price * quantity
def calculate_discount(subtotal, percentage):
return subtotal * percentage / 100
price = 2000
quantity = 3
subtotal = calculate_subtotal(price, quantity)
discount = calculate_discount(subtotal, 10)
print(f"Subtotal: Rs. {subtotal}")
print(f"Discount: Rs. {discount}")
Subtotal: Rs. 6000 Discount: Rs. 600.0
Breaking a larger task into smaller functions makes programs easier to understand, test, and maintain.
Real-World Examples
Example 1 — Ecommerce Final Price
def calculate_final_price(price, discount):
discount_amount = price * discount / 100
return price - discount_amount
final_price = calculate_final_price(5000, 15)
print(f"Final Price: Rs. {final_price}")
Final Price: Rs. 4250.0
Example 2 — Student Result
def calculate_average(marks):
return sum(marks) / len(marks)
def calculate_grade(average):
if average >= 80:
return "A"
elif average >= 70:
return "B"
elif average >= 60:
return "C"
elif average >= 50:
return "D"
return "F"
marks = [85, 78, 92, 88, 80]
average = calculate_average(marks)
grade = calculate_grade(average)
print(f"Average: {average:.2f}")
print(f"Grade: {grade}")
Average: 84.60 Grade: A
Example 3 — Login Validation
def validate_login(username, password):
if username == "admin" and password == "1234":
return True
return False
if validate_login("admin", "1234"):
print("Login successful")
else:
print("Invalid credentials")
Login successful
Real applications should use secure password storage and authentication systems rather than hard-coded passwords.
Common Return Mistakes
1. Using print instead of return
def add(a, b):
print(a + b)
result = add(5, 10)
print(result)
The function displays the answer but returns
None.
2. Code after return does not execute
def example():
return 10
print("This will not run")
Once return executes, the function ends.
3. Returning too early
def check_numbers(numbers):
for number in numbers:
if number > 10:
return True
return False
Here, the return False is inside the loop, so
the function stops after checking the first item that does
not satisfy the condition.
def check_numbers(numbers):
for number in numbers:
if number > 10:
return True
return False
4. Expecting multiple values without unpacking
Remember that return a, b produces a tuple.
You can unpack it when you want separate variables.
Practice Exercises
Exercise 1 — Square
Create a function that receives a number and returns its square.
Exercise 2 — Even Check
Create a function that returns True if a
number is even and False otherwise.
Exercise 3 — Maximum
Create a function that receives two numbers and returns the larger number.
Exercise 4 — Grade
Create a function that receives a student's score and returns the appropriate grade.
Exercise 5 — Rectangle
Return both the area and perimeter of a rectangle.
Exercise 6 — Search
Create a function that searches a list and returns
True if an item exists.
Exercise 7 — Discount
Create a function that returns the final price after a discount.
Mini Challenge — Sales Summary Generator
Build a small sales analysis program using multiple functions and return values.
🎯 Your Mission
Create functions that:
- Calculate total sales.
- Calculate average sale.
- Find the highest sale.
- Find the lowest sale.
- Return a complete summary.
def calculate_total(sales):
return sum(sales)
def calculate_average(sales):
return sum(sales) / len(sales)
def calculate_highest(sales):
return max(sales)
def calculate_lowest(sales):
return min(sales)
def create_summary(sales):
total = calculate_total(sales)
average = calculate_average(sales)
highest = calculate_highest(sales)
lowest = calculate_lowest(sales)
return total, average, highest, lowest
sales = [12000, 18500, 9000, 22000, 15000]
total, average, highest, lowest = create_summary(sales)
print("----- SALES SUMMARY -----")
print(f"Total Sales: Rs. {total}")
print(f"Average Sale: Rs. {average:.2f}")
print(f"Highest Sale: Rs. {highest}")
print(f"Lowest Sale: Rs. {lowest}")
----- SALES SUMMARY ----- Total Sales: Rs. 76500 Average Sale: Rs. 15300.00 Highest Sale: Rs. 22000 Lowest Sale: Rs. 9000
Add a function that calculates the number of sales, percentage contribution of the highest sale, and returns all information in a dictionary.
Quick Knowledge Check
1. What does the return statement do?
2. What does a function return if it has no return statement?
3. What is the main difference between print() and return?
4. What happens immediately after return executes?
5. What does this return?
def calculate():
return 10, 20
6. Which is a valid way to unpack multiple return values?
7. What does return inside a loop do?
8. Which statement is correct?
Lesson Summary
The return statement allows functions to send
useful results back to the code that called them.
Key Takeaways
-
returnsends a value back to the caller. -
print()displays information but does not return it. - Returned values can be stored in variables.
- Returned values can be used in calculations and conditions.
- Functions can return expressions directly.
- Python can return multiple values by packaging them into a tuple.
- Returned tuples can be unpacked into separate variables.
- A return statement immediately ends the function.
-
Functions without a return statement automatically
return
None. -
returninside a loop exits the entire function, unlikebreak, which exits the current loop.
You now understand the complete flow of input → processing → output inside functions. This is a major step toward writing modular, reusable Python programs.
Next, we will study Scope and understand where variables created inside and outside functions are accessible.
Ready for Lesson 31?
Mark this lesson complete when you are comfortable using
return, storing returned values, and using
functions to produce reusable results.