Monday, August 25, 2025

🐍RETURN VALUES IN FUNCTIONS

Return Values in Python Functions

Until now, our functions only printed results. But often, we want a function to send back a value so we can reuse it later. This is where return comes in.

1) Introduction

In Python, functions can use the return statement to send a value back to the caller. Unlike print(), which just displays something on the screen, return actually hands back data for further use in your program.


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

result = add(5, 3)
print(result)   # Output: 8

Key Difference:

  • print() → only shows output on screen, no reusable value.
  • return → sends result back, can be stored in variables or used in further calculations.

2) Returning Multiple Values

Python allows returning multiple values separated by commas. These values are packed into a tuple.


def calculate(a, b):
    return a + b, a - b, a * b

result = calculate(10, 5)
print(result)         # (15, 5, 50)

x, y, z = calculate(10, 5)
print(x, y, z)        # 15 5 50

3) Returning None

If a function has no return statement, or just return without value, Python returns None by default.


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

result = greet("Alice")
print(result)   # Output: None

4) Common Mistakes

  • Confusing print and return: Using print() inside a function when you actually need return.
  • Using returned value without assignment: If you don’t store the return, the value is lost.
  • Multiple return statements: Once a return is executed, the function ends immediately.

def test():
    print("Hello")
    return "Bye"
    print("This will never run")

print(test())
# Output:
# Hello
# Bye

💡 Try It Yourself

  1. Write a function that returns the square of a number.
  2. Write a function that returns both the quotient and remainder of two numbers.
  3. Write a function that takes a string and returns both uppercase and lowercase versions.
  4. Modify a function to print and return values, then observe the difference.

🖥️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??