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.
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:If no
def, keyword that defines a functionname, the parameter (input the function expects)return, sends a value back to whoever called the functionreturn, the function returns NoneFunctions 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 = 25Decomposition, 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 solvedExercise 1 of 3easy
โฑ 00:00Celsius to Fahrenheit
Write a function
Formula: F = (C ร 9/5) + 32
to_fahrenheit(celsius) that converts Celsius to Fahrenheit.Formula: F = (C ร 9/5) + 32
solution.py
1 / 3
Exercise 2 of 3medium
โฑ 00:00Is Prime?
Write a function
A prime number is only divisible by 1 and itself. 1 is NOT prime. 2 is prime.
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:00Caesar Cipher
Write a function
Example:
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