free geoip
4

Python Return Statement Exercises

The return statement in Python is one of the most important concepts in functions. It allows a function to send…

The return statement in Python is one of the most important concepts in functions. It allows a function to send a value back to the part of the program where it was called. Understanding how to use return effectively will help you write cleaner, modular, and reusable code. In this tutorial, we will explore various Python return statement exercises with examples to deepen your understanding of how return works in real-world programming.

Python Return Statement Exercises

What Is a Return Statement in Python?

In Python, the return statement is used to exit a function and send back a value to the caller. The general syntax is:

def function_name(parameters):
    # code block
    return value

When a function reaches the return statement, it immediately stops executing and returns the specified value. If there is no return statement, the function automatically returns None.

Example 1: Simple Function with Return

This basic exercise demonstrates how a function can return a calculated result.

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

sum_value = add_numbers(5, 3)
print("The sum is:", sum_value)

Output:

The sum is: 8

Explanation: The function add_numbers() takes two parameters, adds them, and returns the result to the variable sum_value.

Example 2: Returning Multiple Values

Python allows a function to return multiple values separated by commas. These values are automatically packed into a tuple.

def calculate_values(x, y):
    sum_val = x + y
    diff_val = x - y
    prod_val = x * y
    return sum_val, diff_val, prod_val

result = calculate_values(10, 5)
print("Results:", result)

Output:

Results: (15, 5, 50)

Here, calculate_values() returns three different values in a tuple. You can also unpack them individually:

sum_val, diff_val, prod_val = calculate_values(10, 5)
print(sum_val, diff_val, prod_val)

Example 3: Return in Conditional Statements

You can use return inside conditional statements to handle multiple outcomes in your functions.

def check_number(num):
    if num > 0:
        return "Positive"
    elif num < 0:
        return "Negative"
    else:
        return "Zero"

print(check_number(5))
print(check_number(-2))
print(check_number(0))

Output:

Positive
Negative
Zero

Each return statement stops the function once the condition is met.

Example 4: Return and Loops

Here’s how you can use return inside loops to stop execution once a condition is satisfied.

def find_even(numbers):
    for num in numbers:
        if num % 2 == 0:
            return num  # return the first even number found
    return None  # if no even number found

result = find_even([1, 3, 5, 8, 11])
print("First even number:", result)

Output:

First even number: 8

Example 5: Returning a Function Result

You can use return to pass results from one function to another. This technique is often used in larger applications.

def multiply(a, b):
    return a * b

def calculate_total(price, quantity):
    total = multiply(price, quantity)
    return total

result = calculate_total(20, 5)
print("Total Price:", result)

Output:

Total Price: 100

Example 6: Returning Lists or Dictionaries

Functions can also return complex data types like lists or dictionaries.

def get_student_info(name, age, grade):
    return {
        "name": name,
        "age": age,
        "grade": grade
    }

student = get_student_info("Alice", 14, "A")
print(student)

Output:

{'name': 'Alice', 'age': 14, 'grade': 'A'}

Example 7: No Return (Implicit None)

If you don’t specify a return value, Python automatically returns None.

def greet(name):
    print("Hello", name)

result = greet("John")
print(result)

Output:

Hello John
None

Because the function doesn’t have a return statement, Python returns None by default.

Exercise 1: Return Maximum of Three Numbers

Write a function that takes three numbers and returns the largest.

def max_of_three(a, b, c):
    if a >= b and a >= c:
        return a
    elif b >= a and b >= c:
        return b
    else:
        return c

print(max_of_three(5, 9, 3))

Output:

9

Exercise 2: Return Even Numbers from a List

Create a function that returns a list of even numbers from a given list.

def get_even_numbers(numbers):
    evens = []
    for num in numbers:
        if num % 2 == 0:
            evens.append(num)
    return evens

print(get_even_numbers([1, 2, 3, 4, 5, 6]))

Output:

[2, 4, 6]

Exercise 3: Return Factorial of a Number

Here’s a classic recursion example using return to compute factorial values.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))

Output:

120

Conclusion

The Python return statement is fundamental for writing flexible and powerful functions. By completing these exercises, you now understand how to use return to output values, control program flow, and even combine multiple function results together. Mastering this concept is a key step in becoming a proficient Python programmer.

Continue practicing by modifying these examples, adding user inputs, or integrating them into larger Python projects. The more you practice, the more naturally you’ll understand how return shapes your code logic.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *