Chapter 5: Functions — Naming and Reusing Code Blocks¶
What is a Function?¶
A function is a named block of code.
Instead of repeating the same code, you define it once and call it as many times as you need.
Math Functions and Python Functions¶
In math, f(x) = 2x means "take x and return twice the value."
def f(x):
return x * 2
print(f(3)) # 6
print(f(10)) # 20
Once defined, a function can be called any number of times.
Functions We Already Use — Built-in Functions¶
Python comes with built-in functions ready to use.
No installation, no import needed.
print(abs(-5)) # 5
print(len("Python")) # 6
print(min(3, 1, 4)) # 1
print(max(3, 1, 4)) # 4
print(int("42")) # 42
print(str(3.14)) # 3.14
print(float("2.5")) # 2.5
print(list(range(3))) # [0, 1, 2]
Three Categories of Functions¶
| Category | Description | How to Use |
|---|---|---|
| Built-in | Included in Python itself | Use directly |
| Standard Library | Bundled with Python installation | import first |
| External Library | Must be installed separately | pip install then import |
| User-defined | Functions you write | Define with def then call |
Modules — Loading with import¶
Standard library functions must be loaded with import.
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
import random
print(random.randint(1, 6)) # random integer 1-6 (like a die)
Three Ways to Import¶
import math # import the whole module
print(math.sqrt(9)) # module.function()
from math import sqrt # import just one function
print(sqrt(9)) # function() directly
import math as m # import with an alias
print(m.sqrt(9)) # alias.function()
Defining Functions — def¶
def function_name(parameter):
code to execute
return value
def greet(name):
return "Hello, " + name + "!"
result = greet("Alice")
print(result) # Hello, Alice!
The DRY Principle — Don't Repeat Yourself¶
# Bad: repeated code
print("Welcome, Alice!")
print("Welcome, Bob!")
print("Welcome, Charlie!")
# Good: use a function
def welcome(name):
print(f"Welcome, {name}!")
welcome("Alice")
welcome("Bob")
welcome("Charlie")
DRY = Don't Repeat Yourself — if code repeats, wrap it in a function.
How a Function Executes¶
When a function is called, Python follows 4 steps.
1. Evaluate the arguments
2. Create a new namespace
3. Bind arguments to parameters
4. Execute the function body
def add(a, b):
total = a + b
return total
result = add(3, 5)
print(result) # 8
call: add(3, 5)
-> a = 3, b = 5 (new namespace)
-> total = 8
-> return 8
result = 8
Local vs Global Variables — Scope¶
Variables created inside a function are invisible outside it.
x = 10 # global variable
def f():
y = 20 # local variable
print(x) # global variables can be read inside a function
print(y)
f()
# print(y) # Error! y is not accessible outside f()
10
20
| Local Variable | Global Variable | |
|---|---|---|
| Defined inside | Function | Module level |
| Accessible | Only within the function | Readable anywhere |
| Lifetime | Only while function runs | Until program ends |
The global Keyword¶
To modify a global variable inside a function, declare it with global.
count = 0
def increment():
global count # declare count as global
count += 1
increment()
increment()
print(count) # 2
Without global, modifying a global variable causes UnboundLocalError.
count = 0
def bad_increment():
count += 1 # Error! local variable referenced before assignment
bad_increment()
When There's No Return Value — None¶
If a function has no return statement (or just return alone), it returns None.
def say_hello():
print("Hello!")
result = say_hello()
print(result) # None
Hello!
None
None is Python's special value meaning "nothing."
print(type(None)) # <class 'NoneType'>
print(None == 0) # False
print(None == "") # False
Parameters vs Arguments¶
| Term | Where | Example |
|---|---|---|
| Parameter | Function definition | name in def greet(name): |
| Argument | Function call | "Alice" in greet("Alice") |
def bmi(height, weight): # parameters
return weight / (height ** 2)
result = bmi(1.70, 80) # arguments
print(round(result, 1)) # 27.7
Default Values¶
Parameters can have default values.
def greet(name, lang="en"):
if lang == "ko":
return f"Hi, {name}!"
else:
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice! (lang defaults to "en")
print(greet("Bob", "ko")) # Hi, Bob!
Practice Missions¶
Mission 1: Celsius to Fahrenheit¶
def celsius_to_fahrenheit(c):
# Formula: F = C * 9/5 + 32
pass
def fahrenheit_to_celsius(f):
# Formula: C = (F - 32) * 5/9
pass
print(celsius_to_fahrenheit(0)) # 32.0
print(celsius_to_fahrenheit(100)) # 212.0
print(fahrenheit_to_celsius(98.6)) # 37.0
Mission 2: GCD (Greatest Common Divisor)¶
def gcd(a, b):
# Use Euclid's algorithm
# while b != 0:
# a, b = b, a % b
pass
print(gcd(48, 18)) # 6
print(gcd(100, 75)) # 25
Mission 3: Score Validation¶
def is_valid_score(score):
# Return True if score is between 0 and 100 (inclusive), False otherwise
pass
print(is_valid_score(85)) # True
print(is_valid_score(-1)) # False
print(is_valid_score(101)) # False
Mission 4: Returning Multiple Values¶
import math
def circle_info(r):
# Return (circumference, area) as a tuple
# circumference = 2 * pi * r, area = pi * r^2
pass
circumference, area = circle_info(5)
print(round(circumference, 2)) # 31.42
print(round(area, 2)) # 78.54
Mission 5 (Advanced): Recursive Function¶
def factorial(n):
# n! = n * (n-1) * ... * 1
# Implement using recursion
pass
print(factorial(5)) # 120
print(factorial(0)) # 1
Key Summary¶
| Concept | Description |
|---|---|
def name(params): |
Define a function |
return value |
Return a value and exit the function |
| Built-in functions | abs(), len(), min(), max() — no import needed |
import |
Load standard/external libraries |
| Local variable | Exists only inside the function |
| Global variable | Defined outside functions, readable everywhere |
global |
Allow modifying a global variable inside a function |
None |
Returned when there is no return statement |
| Parameter | Named input in the function definition |
| Argument | Actual value passed when calling the function |
| DRY | Don't Repeat Yourself — wrap repeated code in functions |