python

examples

examples.py🐍
"""
05 - Functions: Examples
Run this file to see all function concepts in action!
"""

print("=" * 60)
print("FUNCTIONS - EXAMPLES")
print("=" * 60)

# =============================================================================
# 1. BASIC FUNCTIONS
# =============================================================================
print("\n--- 1. Basic Functions ---\n")

# Simple function (no parameters, no return)
def greet():
    print("Hello, World!")

greet()

# Function with parameter
def greet_person(name):
    print(f"Hello, {name}!")

greet_person("Alice")

# Function with return value
def add(a, b):
    return a + b

result = add(3, 5)
print(f"3 + 5 = {result}")

# Multiple return values
def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers)

minimum, maximum, total = get_stats([1, 2, 3, 4, 5])
print(f"Stats: min={minimum}, max={maximum}, sum={total}")

# =============================================================================
# 2. PARAMETERS AND ARGUMENTS
# =============================================================================
print("\n--- 2. Parameters and Arguments ---\n")

# Positional arguments
def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type} named {pet_name}")

describe_pet("dog", "Buddy")

# Keyword arguments
describe_pet(pet_name="Whiskers", animal_type="cat")

# Default parameters
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Alice")
greet("Bob", "Hi")
greet("Charlie", greeting="Hey")

# Function with many defaults
def make_pizza(size="medium", *toppings):
    print(f"\nMaking a {size} pizza with:")
    for topping in toppings:
        print(f"  - {topping}")

make_pizza("large", "pepperoni", "mushrooms", "olives")
make_pizza("small", "cheese")

# =============================================================================
# 3. *ARGS AND **KWARGS
# =============================================================================
print("\n--- 3. *args and **kwargs ---\n")

# *args - variable positional arguments
def sum_all(*numbers):
    print(f"Received args: {numbers}")
    return sum(numbers)

print(f"sum_all(1, 2, 3) = {sum_all(1, 2, 3)}")
print(f"sum_all(1, 2, 3, 4, 5) = {sum_all(1, 2, 3, 4, 5)}")

# **kwargs - variable keyword arguments
def print_info(**info):
    print("Received kwargs:")
    for key, value in info.items():
        print(f"  {key}: {value}")

print_info(name="Alice", age=25, city="NYC")

# Combining all types
def example(required, *args, default="value", **kwargs):
    print(f"required: {required}")
    print(f"args: {args}")
    print(f"default: {default}")
    print(f"kwargs: {kwargs}")

print("\nCombined example:")
example("req", 1, 2, 3, default="custom", x=10, y=20)

# Unpacking arguments
def add_three(a, b, c):
    return a + b + c

numbers = [1, 2, 3]
print(f"\nUnpacking list: {add_three(*numbers)}")

params = {"a": 10, "b": 20, "c": 30}
print(f"Unpacking dict: {add_three(**params)}")

# =============================================================================
# 4. LAMBDA FUNCTIONS
# =============================================================================
print("\n--- 4. Lambda Functions ---\n")

# Basic lambda
square = lambda x: x ** 2
print(f"square(5) = {square(5)}")

# Lambda with multiple parameters
add = lambda x, y: x + y
print(f"add(3, 4) = {add(3, 4)}")

# Using lambda with sorted()
students = [
    ("Alice", 85),
    ("Bob", 92),
    ("Charlie", 78),
    ("David", 95)
]
print(f"\nOriginal: {students}")
print(f"Sorted by name: {sorted(students, key=lambda x: x[0])}")
print(f"Sorted by score: {sorted(students, key=lambda x: x[1])}")
print(f"Sorted by score (desc): {sorted(students, key=lambda x: x[1], reverse=True)}")

# Using lambda with map()
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(f"\nSquared: {squared}")

# Using lambda with filter()
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")

# Using lambda with reduce()
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
print(f"Product: {product}")

# =============================================================================
# 5. RECURSION
# =============================================================================
print("\n--- 5. Recursion ---\n")

# Factorial
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(f"5! = {factorial(5)}")
print(f"10! = {factorial(10)}")

# Fibonacci
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print("\nFibonacci sequence (first 10):")
print([fibonacci(i) for i in range(10)])

# Sum of list (recursive)
def sum_recursive(lst):
    if not lst:
        return 0
    return lst[0] + sum_recursive(lst[1:])

print(f"\nsum_recursive([1,2,3,4,5]) = {sum_recursive([1,2,3,4,5])}")

# Countdown
def countdown(n):
    if n <= 0:
        print("Liftoff!")
    else:
        print(n)
        countdown(n - 1)

print("\nCountdown:")
countdown(5)

# =============================================================================
# 6. DECORATORS
# =============================================================================
print("\n--- 6. Decorators ---\n")

import time

# Basic decorator
def uppercase_result(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result.upper()
    return wrapper

@uppercase_result
def greet(name):
    return f"Hello, {name}"

print(greet("Alice"))

# Timer decorator
def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.6f} seconds")
        return result
    return wrapper

@timer
def slow_sum(n):
    return sum(range(n))

slow_sum(1000000)

# Debug decorator
def debug(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}({args}, {kwargs})")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

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

print(f"\nResult: {multiply(3, 4)}")

# Decorator with arguments (using a factory)
def repeat(times):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@repeat(times=3)
def say_hi():
    print("Hi!")

print("\nRepeat decorator:")
say_hi()

# =============================================================================
# 7. HIGHER-ORDER FUNCTIONS
# =============================================================================
print("\n--- 7. Higher-Order Functions ---\n")

# Function that returns a function
def multiplier(factor):
    def multiply(x):
        return x * factor
    return multiply

double = multiplier(2)
triple = multiplier(3)

print(f"double(5) = {double(5)}")
print(f"triple(5) = {triple(5)}")

# Function that takes a function
def apply_operation(numbers, operation):
    return [operation(x) for x in numbers]

numbers = [1, 2, 3, 4, 5]
print(f"\nOriginal: {numbers}")
print(f"Squared: {apply_operation(numbers, lambda x: x**2)}")
print(f"Doubled: {apply_operation(numbers, lambda x: x*2)}")
print(f"Plus 10: {apply_operation(numbers, lambda x: x+10)}")

# =============================================================================
# 8. DOCSTRINGS
# =============================================================================
print("\n--- 8. Docstrings ---\n")

def calculate_area(length, width):
    """
    Calculate the area of a rectangle.
    
    Args:
        length (float): The length of the rectangle.
        width (float): The width of the rectangle.
    
    Returns:
        float: The area of the rectangle.
    
    Example:
        >>> calculate_area(5, 3)
        15
    """
    return length * width

print(f"calculate_area(5, 3) = {calculate_area(5, 3)}")
print(f"\nDocstring:\n{calculate_area.__doc__}")

# =============================================================================
# 9. PRACTICAL EXAMPLES
# =============================================================================
print("\n--- 9. Practical Examples ---\n")

# Example 1: Memoization (caching)
def memoize(func):
    cache = {}
    def wrapper(n):
        if n not in cache:
            cache[n] = func(n)
        return cache[n]
    return wrapper

@memoize
def fibonacci_memo(n):
    if n <= 1:
        return n
    return fibonacci_memo(n - 1) + fibonacci_memo(n - 2)

print("Fibonacci with memoization:")
print([fibonacci_memo(i) for i in range(20)])

# Example 2: Validator function
def validate_range(min_val, max_val):
    def validator(value):
        if min_val <= value <= max_val:
            return True, "Valid"
        return False, f"Value must be between {min_val} and {max_val}"
    return validator

age_validator = validate_range(0, 120)
print(f"\nValidate age 25: {age_validator(25)}")
print(f"Validate age 150: {age_validator(150)}")

# Example 3: Compose functions
def compose(*functions):
    def inner(arg):
        result = arg
        for f in reversed(functions):
            result = f(result)
        return result
    return inner

add_one = lambda x: x + 1
double = lambda x: x * 2
square = lambda x: x ** 2

composed = compose(square, double, add_one)
print(f"\ncompose(square, double, add_one)(3) = {composed(3)}")
# (3 + 1) = 4, 4 * 2 = 8, 8^2 = 64

print("\n" + "=" * 60)
print("END OF EXAMPLES")
print("=" * 60)
Examples - Python Tutorial | DeepML