Home Course Roadmap
Lesson 30 · Functions

Python Return Values

Learn how Python functions send results back to the code that called them using the powerful return statement.

40–50 minutes Beginner Functions
0%

What You'll Learn

  • Understand how the return statement works.
  • Understand the difference between print() and return.
  • 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.
01

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.

Basic Return
def add(a, b):
    return a + b

result = add(10, 20)

print(result)
Output
30

The function calculates a + b and returns the result to the caller.

Core idea:

A function can receive data through parameters, process that data, and send a result back using return.

03

Basic Return Values

A function can return numbers, strings, Boolean values, lists, dictionaries, and many other Python objects.

Returning a number

Number
def get_score():
    return 95

score = get_score()

print(score)

Returning a string

String
def get_message():
    return "Welcome to PyLearn"

message = get_message()

print(message)

Returning a Boolean

Boolean
def is_adult(age):
    return age >= 18

print(is_adult(25))
Output
True
04

Storing Returned Values

A returned value can be stored in a variable.

Store the Result
def multiply(a, b):
    return a * b

product = multiply(8, 5)

print(product)
Output
40

Once stored, the returned value can be used anywhere the variable can be used.

Reuse the Result
def multiply(a, b):
    return a * b

product = multiply(8, 5)

print(product)
print(product + 10)
print(product * 2)
Output
40
50
80
05

Using Returned Values

Returned values can be used directly in calculations, conditions, assignments, and other function calls.

Using a return value in a calculation

Calculation
def square(number):
    return number * number

result = square(6) + 10

print(result)
Output
46

Using a return value in a condition

Condition
def is_even(number):
    return number % 2 == 0

if is_even(10):
    print("The number is even.")
Output
The number is even.
06

Returning Expressions

You do not need to create a separate variable before returning a result.

Return an Expression
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.

Complex Expression
def calculate_final_price(price, discount):
    return price - (price * discount / 100)
07

Returning Multiple Values

Python allows a function to appear to return multiple values.

In reality, Python packages the returned values into a tuple.

Multiple Return Values
def calculate(a, b):
    total = a + b
    difference = a - b

    return total, difference

result = calculate(20, 5)

print(result)
Output
(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.

08

Unpacking Returned Values

Because multiple returned values are packaged into a tuple, you can unpack them into separate variables.

Tuple Unpacking
def calculate(a, b):
    return a + b, a - b

total, difference = calculate(20, 5)

print(total)
print(difference)
Output
25
15

This is a clean and useful Python pattern when a function needs to provide several related results.

09

Early return

A return statement immediately ends the execution of the current function.

Early Return
def check_number(number):

    if number < 0:
        return "Negative"

    return "Positive or Zero"

print(check_number(-5))
print(check_number(10))
Output
Negative
Positive or Zero

When number < 0 is true, the function returns immediately. The code after that return is not executed for that call.

Important:

Once Python executes return, the function stops immediately.

10

Conditional Return Values

Functions can return different values depending on conditions.

Grade Function
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))
Output
A
B
F

Each execution follows the appropriate condition and returns a result.

11

Functions Without return

A function does not have to contain a return statement.

No Return Statement
def greet():
    print("Hello!")

result = greet()

print(result)
Output
Hello!
None

If a function finishes without executing a return statement, Python automatically returns None.

12

Returning None

You can explicitly return None when a function needs to indicate that there is no meaningful result.

Explicit None
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)
Output
None

Returning None clearly communicates that the requested item was not found.

Professional pattern:

Many Python functions use None to represent the absence of a result.

13

return with Loops

A return statement can be used inside a loop to immediately finish the entire function.

Search 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))
Output
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.

14

Functions Calling Other Functions

One function can call another function and use the value it returns.

Function Composition
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}")
Output
Subtotal: Rs. 6000
Discount: Rs. 600.0

Breaking a larger task into smaller functions makes programs easier to understand, test, and maintain.

15

Real-World Examples

Example 1 — Ecommerce Final Price

Shopping Calculation
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}")
Output
Final Price: Rs. 4250.0

Example 2 — Student Result

Student Average
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}")
Output
Average: 84.60
Grade: A

Example 3 — Login Validation

Validation Function
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")
Output
Login successful
Learning example:

Real applications should use secure password storage and authentication systems rather than hard-coded passwords.

16

Common Return Mistakes

1. Using print instead of return

Problem
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

Problem
def example():
    return 10

    print("This will not run")

Once return executes, the function ends.

3. Returning too early

Think Carefully
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.

Better approach:
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.

17

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.

18

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.
Suggested Solution
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}")
Expected Output
----- SALES SUMMARY -----
Total Sales: Rs. 76500
Average Sale: Rs. 15300.00
Highest Sale: Rs. 22000
Lowest Sale: Rs. 9000
Challenge extension:

Add a function that calculates the number of sales, percentage contribution of the highest sale, and returns all information in a dictionary.

19

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?

20

Lesson Summary

The return statement allows functions to send useful results back to the code that called them.

Key Takeaways

  • return sends 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.
  • return inside a loop exits the entire function, unlike break, 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.