Lesson 25/48 ยท โš™๏ธ Functions
โš™๏ธ FunctionsLesson 25/48
Phase 4 ยท Functions30 min

Functions, Reusable Building Blocks

Break your code into small, named, reusable pieces

A function is a named block of code that does one specific job. Instead of writing the same logic over and over, you define it once and call it by name.
The golden rule: One function = one job.

How would you approach this? Think first, then expand.

Defining and calling a functionpython
def greet(name):
    message = f"Hello, {name}!"
    return message

# Call the function
result = greet("Alice")
print(result)   # Hello, Alice!
print(greet("Bob"))  # Hello, Bob!
๐Ÿ”Code TracerStep 1 / 7
trace.py
1def greet(name):โ†
2 return f"Hello, {name}!"
3
4result = greet("Bob")
5print(result)
Variables
No variables yet
Step 1 / 7
Key terms:
  • def, keyword that defines a function
  • name, the parameter (input the function expects)
  • return, sends a value back to whoever called the function
  • If no return, the function returns None
  • Functions calling other functionspython
    def square(n):
        return n * n
    
    def sum_of_squares(a, b):
        return square(a) + square(b)   # reuse square()
    
    print(sum_of_squares(3, 4))  # 9 + 16 = 25
    Decomposition, breaking a big problem into small functions, is the single most important skill in programming. If a function is more than ~10 lines, think about whether it should be split into smaller ones.
    ๐ŸŒIn the Real World...

    Every reusable Terraform module, every Helm template helper, every CI script utility follows this pattern: one job, clear inputs, clear output. The same mental model, different syntax.

    Practice Exercises

    0/3 solved
    Exercise 1 of 3easy
    โฑ 00:00

    Celsius to Fahrenheit

    Write a function to_fahrenheit(celsius) that converts Celsius to Fahrenheit.
    Formula: F = (C ร— 9/5) + 32
    solution.py
    1 / 3
    Exercise 2 of 3medium
    โฑ 00:00

    Is Prime?

    Write a function is_prime(n) that returns True if n is prime, False otherwise.
    A prime number is only divisible by 1 and itself. 1 is NOT prime. 2 is prime.
    solution.py
    2 / 3
    Exercise 3 of 3hard
    โฑ 00:00

    Caesar Cipher

    Write a function caesar(text, shift) that encrypts a string by shifting each letter by shift positions in the alphabet. Non-letters stay unchanged.
    Example: caesar("Hello", 3) โ†’ "Khoor"
    solution.py
    3 / 3
    Solve all 3 exercises to unlock completion