P

Functions & Generators

Python syntax guide

Function definitions and generator functions in Python

Functions & Generators

Function definitions and generator functions in Python

Python functions & generators (python)
        
          # Function definition
def greet(name, greeting="Hello"):
    """Function with docstring and default parameter"""
    return f"{greeting}, {name}!"

# Function with *args and **kwargs
def flexible_function(*args, **kwargs):
    print("Positional args:", args)
    print("Keyword args:", kwargs)

flexible_function(1, 2, 3, name="John", age=25)

# Lambda functions
square = lambda x: x ** 2
print(square(5))  # 25

# Generator function
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num, end=" ")  # 0 1 1 2 3 5 8 13 21 34

# Generator expression
squares_gen = (x**2 for x in range(10))
print(list(squares_gen))  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

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

@timer
def slow_function():
    import time
    time.sleep(1)
    return "Done"

slow_function()
        
      

Explanation

Python functions support default parameters, *args, and **kwargs. Generators use yield for memory-efficient iteration. Decorators modify function behavior.

Common Use Cases

  • Code reusability
  • Memory-efficient iteration
  • Function modification
  • Performance monitoring

Related Python Syntax

Master Functions & Generators in Python

Understanding functions & generators is fundamental to writing clean and efficient Python code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using functions & generators effectively in your Python projects.

Key Takeaways

  • Code reusability
  • Memory-efficient iteration
  • Function modification