KAHIBARO Bookshelves
Discord Login Register

9.4. Return values

Why Return Values Matter

When you call a function, it can do two main things:

  1. Perform some actions (print text, write to a file, etc.).
  2. Give back a result that you can use later in your code.

That “giving back a result” is called returning a value.

A function’s return value is what you get back when you call it, and you can store it in a variable, use it in a calculation, or pass it to another function.

Many built‑in functions you already know use return values:

  • len("hello") returns 5
  • int("42") returns 42
  • max(3, 10, 7) returns 10

The `return` Statement

Inside a function, you use the return keyword to send a value back to the caller.

Basic pattern:

def function_name():
    # do some work
    return something  # send 'something' back

Example:

def add(a, b):
    result = a + b
    return result
sum_of_numbers = add(3, 5)  # sum_of_numbers will be 8
print(sum_of_numbers)

Key idea: return passes a value out of the function to wherever the function was called.

You can also return an expression directly:

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

Using Return Values vs. Printing

New programmers often confuse returning with printing.

  • print() shows something on the screen.
  • return sends a value back from a function so your program can use it.

Compare:

def add_and_print(a, b):
    result = a + b
    print(result)  # only shows it, does NOT return
def add_and_return(a, b):
    return a + b   # returns the sum
# Using the first function:
x = add_and_print(2, 3)
print("x is:", x)

Output:

5
x is: None

Explanation:

  • add_and_print(2, 3) prints 5, but doesn’t return anything.
  • In Python, a function that doesn’t return a value automatically returns None.
  • So x becomes None.

With add_and_return:

y = add_and_return(2, 3)
print("y is:", y)

Output:

y is: 5

Use printing for user messages, debugging, and results you want to see.
Use return values for data you want to reuse and combine in your program.

Functions That Return Nothing: `None`

If a function has no return statement, or has a return with no value, Python returns None.

def say_hello(name):
    print("Hello,", name)
result = say_hello("Alice")
print("result is:", result)

Output:

Hello, Alice
result is: None

You can also write:

def do_nothing():
    return  # no value
value = do_nothing()
print(value)   # None

None is a special value in Python that means “nothing” or “no value”.

Functions that are meant to perform an action (like printing, writing to a file, etc.) often return None.
Functions that are meant to calculate something should usually return a meaningful value instead.

Returning Different Types of Values

A function can return any type of value: numbers, strings, booleans, lists, dictionaries, and more.

Returning a number

def area_of_rectangle(width, height):
    return width * height
area = area_of_rectangle(4, 3)
print(area)  # 12

Returning a string

def greeting(name):
    return "Hello, " + name + "!"
msg = greeting("Sam")
print(msg)  # Hello, Sam!

Returning a boolean

def is_even(n):
    return n % 2 == 0
print(is_even(4))  # True
print(is_even(7))  # False

Returning a list or other collections

def first_and_last(text):
    return [text[0], text[-1]]
result = first_and_last("Python")
print(result)  # ['P', 'n']

Returning Multiple Values

Python functions can only return one object, but that object can be a tuple (or list, etc.) that contains multiple pieces of data. This is often written as if returning “multiple values”.

def divide_and_remainder(a, b):
    quotient = a // b
    remainder = a % b
    return quotient, remainder   # returns a tuple: (quotient, remainder)
q, r = divide_and_remainder(17, 5)
print("Quotient:", q)   # 3
print("Remainder:", r)  # 2

Here, divide_and_remainder(17, 5) returns the tuple (3, 2), and Python unpacks it into q and r.

You can also capture the tuple directly:

result = divide_and_remainder(17, 5)
print(result)      # (3, 2)
print(result[0])   # 3
print(result[1])   # 2

How `return` Ends a Function Early

As soon as Python reaches a return statement inside a function, it:

  1. Evaluates the value (if any) after return.
  2. Immediately exits the function.
  3. Sends that value back to the caller.

Any code after return in the same block will not run.

def test_return():
    print("Before return")
    return 42
    print("After return")  # this line never runs
value = test_return()
print("Returned:", value)

Output:

Before return
Returned: 42

You can use this behavior to exit a function early in certain situations.

Example: validating input

def safe_divide(a, b):
    if b == 0:
        print("Cannot divide by zero.")
        return None   # exit early with a special value
    return a / b
print(safe_divide(10, 0))   # message + None
print(safe_divide(10, 2))   # 5.0

Designing Functions With Useful Return Values

When writing a function, a good question to ask:

“What should this function give back?”

Some common patterns:

Compute and return a result

def average(a, b, c):
    return (a + b + c) / 3
avg = average(10, 20, 30)
print(avg)  # 20.0

Return a “success or failure” flag

def is_valid_age(age):
    return age >= 0 and age <= 120
print(is_valid_age(25))   # True
print(is_valid_age(-1))   # False

Return data instead of printing it

Instead of:

def make_full_name(first, last):
    print(first + " " + last)

Prefer:

def make_full_name(first, last):
    return first + " " + last
full = make_full_name("Ada", "Lovelace")
print("Full name:", full)

Returning data makes your function more flexible: you can print it, store it, compare it, or send it somewhere else.

Common Mistakes With Return Values

1. Forgetting to return

def add(a, b):
    result = a + b  # computed, but never returned
sum_value = add(2, 3)
print(sum_value)   # None

Fix:

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

2. Thinking `print` is the same as `return`

def square(n):
    print(n * n)   # only displays it
result = square(4)
print("result:", result)  # result: None

Fix:

def square(n):
    return n * n

3. Code after `return` expecting to run

def example():
    return 10
    print("This will never happen")

Anything after return in the same block is unreachable and should be removed or moved before return.

Simple Practice Ideas

Here are some small function ideas you can try to practice return values:

  • fahrenheit_to_celsius(f)
    Return the Celsius temperature.
  • full_name(first, last)
    Return a combined "First Last" string.
  • is_adult(age)
    Return True if age is at least 18, otherwise False.
  • min_max(a, b, c)
    Return both the smallest and largest of three numbers (for example as a tuple (min_value, max_value)).
  • count_char(text, char)
    Return how many times a character appears in a string.

Focus on:

  • Using return instead of print when you want to use the result.
  • Choosing clear and useful values to return.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms