Level: Basic | Player: Week 8 (All grammar up to now)
Learning Goals
- Define and call the function with
def - Understand the difference between parameters and arguments
- Use default parameters and keyword arguments
- Returns the value as
return - Understand the scope of variables (Region/Area)
1. What is a Function
Instead of using the same action multiple times, name it and reuse it. This makes the code short and clear.
def greet(name):
print(f"Hello, {name}!")
greet("Hong Gil-dong")
greet("Kim Young-hee")
2. Parameters and Arguments
- Parameter: A variable in a function definition (
name) - Argument: The value passed when calling a function (
"Hong Gil-dong")
def add(a, b): #a, b: parameters
return a + b
result = add(3, 5) #3, 5: arguments
3. return
The function returns a value. Terminates immediately when it encounters return.
def square(x):
return x * x
n = square(5) # 25
If return is not available, None is returned automatically.
4. Default Parameters
If arguments are omitted when calling, the default values are used.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Gildong")) #Hello, Gildong!
print(greet("Alice", "Hello")) #Hello, Alice!
5. Keyword Arguments
Deliver by name instead of order.
def make_user(name, age, city):
return {"name": name, "age": age, "city": city}
#Positional argument
u1 = make_user("Hong Gil-dong", 20, "Seoul")
#Keyword argument (order does not matter, easy to read)
u2 = make_user(city="Busan", name="Kim Young-hee", age=25)
6. Returning Multiple Values (Tuple)
def min_max(nums):
return min(nums), max(nums)
lo, hi = min_max([3, 1, 4, 1, 5])
print(lo, hi) # 1 5
7. Variable Scope
A variable created inside a function is a local variable — it is not visible outside.
def f():
x = 10 #Region
print(x)
f()
# print(x) # NameError
To modify a global variable inside a function, the global keyword:
total = 0
def add(n):
global total
total += n
(If possible, avoid global, and it is recommended that the function takes a value and returns it.)
Key Examples (examples/)
| File | Content |
|---|---|
01_basic_function.py |
Definition·Call |
02_default_args.py |
Default parameter |
03_return.py |
return / multiple return values |
04_scope.py |
Region/Area variable |
⚠️ Common Mistakes
-
Omitting
()in function calldef hi(): print("hi") hi #Function object. Does not execute hi() #Execute -
Using result without
returndef show(x): print(x) y = show(5) # y = None -
Mutable object as default value
def add_to(item, lst=[]): #⚠️ Trap! lst.append(item) return lst add_to(1) # [1] add_to(2) #[1, 2] — The same list is shared
→ Set default as None and create a new one inside the function:
def add_to(item, lst=None):
if lst is None:
lst = []
...
- Name collision
def list(): #Internal list hidden ...
→ Do not use built-in names like print, list, sum for variables or functions.
❓ FAQ
Q1. How many lines are appropriate for a function? A. Recommended 5–30 lines. If it's too long, split into smaller functions.
Q2. What is the difference between print and return?
A. print prints to the screen, return returns a value. Use return when the function itself needs the value.
Q3. Can a function call another function inside it? A. Yes. It can also call itself (recursion) (covered in intermediate level).
📝 Exercises (exercises/)
exercise1.md— collection of calculator functionsexercise2.md— input validation functions (is_valid_age)exercise3.md— prime number detection function (is_prime)
Next Week
Week 10. Comprehensive Practice — mini project