Work with returned values in Python functions: how to transmit data back to the calling code

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Return values in Python: a complete guide with examples

The return values in Python are the data that the function sends back to the calling code after completing its work. Understanding the value return mechanism is a fundamental skill for any Python programmer.

What are return values in Python

The return values allow functions to transfer the results of their calculations back to the main program. This makes the code more modular, readable, and allows you to reuse functions in different parts of the program.

Basics of using the return keyword

Simple return of a single value

To return a value from a function, the return keyword is used. The function can return any type of Python data:

def add_numbers(x, y):
"""Function for adding two numbers"""
return x + y

# Using the function
result = add_numbers(3, 4)
print(result) # Output: 7

# Return the string
def get_greeting(name):
    return f"Hello, {name}!"

message = get_greeting("Anna")
print(message) # Output: Hello, Anna!

Return of various data types

Python allows you to return any type of data:

def get_user_info():
"""Return dictionary with user information"""
return {
        "name": "Ivan",
        "age": 25,
        "skills": ["Python", "JavaScript", "SQL"]
    }

user_data = get_user_info()
print(user_data["name"]) # Output: Ivan

def create_number_list(n):
"""Return a list of numbers"""
return [i for i in range(1, n + 1)]

numbers = create_number_list(5)
print(numbers) # Output: [1, 2, 3, 4, 5]

Return multiple values

One of the powerful features of Python is the ability to return multiple values at the same time:

def calculate_operations(x, y):
"""Performs basic mathematical operations"""
addition = x + y
    subtraction = x - y
    multiplication = x * y
    division = x / y if y != 0 else None
    
    return addition, subtraction, multiplication, division

# Getting all the values in the tuple
results = calculate_operations(10, 3)
print(results) # Output: (13, 7, 30, 3.3333333333333335)

# Unpacking values into separate variables
sum_val, diff_val, mult_val, div_val = calculate_operations(10, 3)
print(f"Sum: {sum_val}")        # Withdrawal: Amount: 13
print(f"Difference: {diff_val}")    # Output: Difference: 7
print(f"Product: {mult_val}") # Output: Product: 30

Returning named tuples

Named tuples can be used to improve code readability.:

from collections import namedtuple

def analyze_numbers(numbers):
"""Analyzing a list of numbers"""
    Statistics = namedtuple('Statistics', ['min_val', 'max_val', 'avg_val', 'count'])
    
    return Statistics(
        min_val=min(numbers),
        max_val=max(numbers),
        avg_val=sum(numbers) / len(numbers),
        count=len(numbers)
    )

data = [1, 5, 3, 9, 2, 7]
stats = analyze_numbers(data)
print(f"Minimum: {stats.min_val}")  # Output: Minimum: 1
print(f"Maximum: {stats.max_val}")  # Output: Maximum: 9

Working with None as a return value

Implicit return None

If the function does not contain the return operator or contains return without a value, it automatically returns None:

def print_message(text):
"""A function that only outputs the message"""
print(f"Message: {text}")

result = print_message("Hello!")
print(f"Result: {result}")  # Output: Result: None

def process_data(data):
"""Conditional return function"""
if not data:
        return # Returns None
    
    # Data processing
    return data.upper()

print(process_data(""))      # Output: None
print(process_data("test"))  # Conclusion: TEST

Explicit check for None

def divide_safely(a, b):
"""Safe division with zero check"""
if b == 0:
return None
    return a / b

result = divide_safely(10, 0)
if result is None:
    print("Division by zero is impossible")
else:
print(f"Result: {result}")

Best practices for working with return values

Consistency of return value types

def get_user_by_id(user_id):
    """Returns user or None"""
users = {1: "Anna", 2: "Peter", 3: "Maria"}
    
    return users.get(user_id) # Returns the value or None

# Proper processing
user = get_user_by_id(1)
if user:
    print(f"User found: {user}")
else:
print("User not found")

Using type annotations

from typing import Tuple, Optional, List

def calculate_stats(numbers: List[int]) -> Tuple[int, int, float]:
    """Calculates statistics on a list of numbers"""
return min(numbers), max(numbers), sum(numbers) / len(numbers)

def find_user(name: str) -> Optional[dict]:
    """Search for a user by name"""
users = [{"name": "Anna", "age": 25}, {"name": "Peter", "age": 30}]
    
    for user in users:
        if user["name"] == name:
            return user
    return None

Advanced techniques for working with return values

Return of functions

def create_multiplier(factor):
"""Creates a multiplier function"""
    def multiplier(number):
        return number * factor
    return multiplier

double = create_multiplier(2)
triple = create_multiplier(3)

print(double(5)) # Output: 10
print(triple(4)) # Output: 12

Return of generators

def fibonacci_generator(n):
"""Fibonacci number generator"""
a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

# Using the generator
fib_gen = fibonacci_generator(10)
for num in fib_gen:
print(num, end=" ") # Output: 0 1 1 2 3 5 8 13 21 34

Error handling when working with return values

Return of the result and operation status

def safe_divide(a, b):
"""Safe division with status return"""
try:
        result = a / b
        return True, result
    except ZeroDivisionError:
        return False, "Division by zero"
    except TypeError:
        return False, "Invalid data type"

success, result = safe_divide(10, 2)
if success:
    print(f"Result: {result}")
else:
print(f"Error: {result}")

Conclusion

Return values in Python are a powerful tool for creating flexible and reusable functions. Using the return operator correctly, understanding the specifics of returning multiple values, and working with None will help you write better and more professional code.

Basic principles of working with return values:

  • Use meaningful names for the return values
  • Maintain consistency of data types
  • Document the return values in the docstring
  • Handle return cases None
  • Use type annotations to improve code readability

Once you have mastered these concepts, you will be able to create more structured and efficient Python programs.

 

categories

  • Introduction to Python
  • Python Programming Basics
  • Control Structures
  • Data Structures
  • Functions and Modules
  • Exception Handling
  • Working with Files and Streams
  • File System
  • Object-Oriented Programming (OOP)
  • Regular Expressions
  • Additional Topics
  • General Python Base