Module 8 of 15 · Python for AI — Complete Beginner Course · Beginner

Functions: Reusable Code

Duration: 5 min

Functions are reusable blocks of code that perform a specific task. They help you organize code, avoid repetition, and make programs easier to understand.

Visual: Control Flow

        ┌─────────────┐
        │   START     │
        └──────┬──────┘
               │
        ┌──────▼──────┐
        │ Condition?  │
        └──┬───────┬──┘
           │       │
        YES│       │NO
           │       │
      ┌────▼──┐ ┌─▼────┐
      │Block1 │ │Block2│
      └────┬──┘ └─┬────┘
           │      │
        ┌──▼──────▼──┐
        │   CONTINUE │
        └─────────────┘

Key Concepts Table

Statement Purpose Example
if Execute if true if x > 5:
elif Else if condition elif x == 5:
else Default case else:
for Loop over sequence for i in range(10):
while Loop while true while x > 0:
break Exit loop break
continue Skip iteration continue

Defining Functions

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

print(greet("Alice"))  # 'Hello, Alice!'

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

print(add(5, 3))  # 8

# Function with default parameters
def power(base, exponent=2):
    return base ** exponent

print(power(5))      # 25 (5^2)
print(power(5, 3))   # 125 (5^3)

# Function with *args (variable arguments)
def sum_all(*numbers):
    total = 0
    for num in numbers:
        total += num
    return total

print(sum_all(1, 2, 3, 4, 5))  # 15

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

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

Try it in Google Colab: Open in Colab

Hello, Alice!
8
25
125
15
name: Alice
age: 25
city: NYC

Lambda Functions (Anonymous Functions)

Lambda functions are small anonymous functions. Use them for simple operations, especially with map(), filter(), and sorted().

Learn more: https://docs.python.org/3/tutorial/

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

# Lambda with map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

# Lambda with filter
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [2, 4]

# Lambda with sorted
people = [("Alice", 25), ("Bob", 20), ("Charlie", 30)]
sorted_by_age = sorted(people, key=lambda x: x[1])
print(sorted_by_age)  # [('Bob', 20), ('Alice', 25), ('Charlie', 30)]
25
[1, 4, 9, 16, 25]
[2, 4]
[('Bob', 20), ('Alice', 25), ('Charlie', 30)]

💡 Tip: Use lambda for simple one-liners. For complex logic, use regular functions.

❓ What does this lambda do? lambda x: x * 2

# Advanced example for Functions: Reusable Code
# Production-ready pattern
print('Advanced implementation')
Advanced implementation

❓ What is a best practice when working with Functions?

💡 Tip: Pro Tip: Master Functions thoroughly before moving to advanced topics. This foundation is crucial for writing professional Python code.

Practice Quizzes

Quiz 1: What does 'elif' stand for?

Quiz 2: How do you exit a loop early?

Quiz 3: What is the difference between 'break' and 'continue'?

← Previous Continue interactively → Next →

Related Courses