📦 Functions and Modules

Functions and modules are the building blocks of organized Python code. They help you create reusable code, avoid repetition, and build maintainable applications by organizing related functionality together.

# Simple function example
def greet(name):
    return f"Hello, {name}!"

# Function with multiple parameters
def calculate_total(price, tax_rate=0.08):
    tax = price * tax_rate
    return price + tax

# Using functions
message = greet("Alice")
total = calculate_total(100, 0.1)

print(message)  # Hello, Alice!
print(f"Total: ${total}")  # Total: $110.0

🎯 Why Functions and Modules Matter

Functions and modules help you:

  • Reuse Code 🔄: Write once, use many times
  • Organize Logic 📁: Group related functionality
  • Easy Testing ✅: Test individual pieces
  • Collaboration 👥: Share code between team members
  • Maintenance 🔧: Easier to update and fix

📚 Functions and Modules Topics

Learn to organize and structure your Python code:

📊 Functions Reference

Function Components

ComponentPurposeExample
NameFunction identifierdef calculate()
ParametersInput valuesdef greet(name, age)
BodyFunction logicIndented code block
ReturnOutput valuereturn result
DocstringDocumentation"""Function description"""

Parameter Types

TypeSyntaxExample
Requiredparamdef func(name):
Defaultparam=valuedef func(name="Guest"):
Variable args*argsdef func(*numbers):
Keyword args**kwargsdef func(**options):

🌟 Quick Examples

Here's what you'll learn to build:

# Function with default parameters
def create_user(name, role="user", active=True):
    return {
        "name": name,
        "role": role,
        "active": active
    }

# Function with *args
def sum_numbers(*numbers):
    return sum(numbers)

# Simple decorator
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

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

# Usage examples
user1 = create_user("Alice")
user2 = create_user("Bob", "admin")

total = sum_numbers(1, 2, 3, 4, 5)
result = multiply(3, 4)

print(f"User1: {user1}")
print(f"Total: {total}")
print(f"Result: {result}")

🏗️ Code Organization Benefits

🚀 Ready to Organize Your Code?

Functions and modules are essential skills for any Python developer. Master these concepts to write cleaner, more maintainable code.

Start your journey: Begin with Write Functions

Build better Python applications with organized, reusable code! 📦✨

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent