Python Series track

Week 09 · Basic Track

Week 9 — Functions

Functions let you name and reuse blocks of logic. Learn def, return, default arguments, keyword arguments, and variable scope (LEGB rule).

Basic Track3 min readFree lesson

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

  1. Omitting () in function call

    def hi():
        print("hi")
    hi    #Function object. Does not execute
    hi()  #Execute
    
  2. Using result without return

    def show(x):
        print(x)
    y = show(5)   # y = None
    
  3. 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 = []
    ...
  1. 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 functions
  • exercise2.md — input validation functions (is_valid_age)
  • exercise3.md — prime number detection function (is_prime)

Next Week

Week 10. Comprehensive Practice — mini project

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

examples/01_basic_function.pyPython
def greet(name):
    print(f"Hello, {name}!")

def add(a, b):
    return a + b

greet("Hong Gil-dong")
greet("Kim Young-hee")

result = add(3, 5)
print(f"3 + 5 = {result}")
examples/02_default_args.pyPython
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Gildong"))
print(greet("Alice", "Hello"))

#Keyword argument
def make_user(name, age, city):
    return {"name": name, "age": age, "city": city}

u1 = make_user("Hong Gil-dong", 20, "Seoul")
u2 = make_user(city="Busan", name="Kim Young-hee", age=25)
print(u1)
print(u2)
examples/03_return.pyPython
def square(x):
    return x * x

def min_max(nums):
    return min(nums), max(nums)

print(square(5))

lo, hi = min_max([3, 1, 4, 1, 5, 9])
print(f"Minimum {lo}, Maximum {hi}")

#return None if not present
def show(x):
    print(x)

y = show(10)
print(f"y = {y}")
examples/04_scope.pyPython
def f():
    x = 10  #Region
    print(f"inside: x = {x}")

f()
# print(x)  # NameError

#global keyword
total = 0

def add_to_total(n):
    global total
    total += n

add_to_total(10)
add_to_total(20)
print(f"total = {total}")

Assignment

Goal

Create arithmetic operation functions and use them in a menu-based calculator.

Requirements

  • 4 functions: add, sub, mul, div
  • div returns None (or a message) if divided by 0
  • Main flow: menu → input two numbers → display result → exit

Input/Output Example

[Menu] 1.+ 2.- 3.* 4./ 5.Exit
Choice: 1
First number: 10
Second number: 5
Result: 15

Assignment 2. Input Validation Function

Goal

Create is_valid_age(value) function.

Requirements

  • If input is an integer between 0 and 120, use True, otherwise False
  • Handle strings as well (e.g., "abc" → False)

Input/Output Example (for test code)

print(is_valid_age(20))      # True
print(is_valid_age(0))       # True
print(is_valid_age(120))     # True
print(is_valid_age(-1))      # False
print(is_valid_age(150))     # False
print(is_valid_age("abc"))   # False

Assignment 3. Prime Number Check Function

Goal

Write is_prime(n) function and print only prime numbers from 1 to 50.

Requirements

  • 1 and numbers less than 0: not prime
  • 2: prime
  • Even numbers (except 2): not prime
  • Others: try dividing by odd numbers from 3 up to √n

Input/Output Example

Prime numbers between 1 and 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

solution1.pyPython
def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b):
    if b == 0:
        return None
    return a / b

while True:
    print("[Menu] 1.+ 2.- 3.* 4./ 5.Exit")
    choice = input("Select:").strip()
    if choice == "5":
        break
    if choice not in {"1", "2", "3", "4"}:
        print("Invalid selection")
        continue
    a = float(input("First number:"))
    b = float(input("Second number:"))
    funcs = {"1": add, "2": sub, "3": mul, "4": div}
    result = funcs[choice](a, b)
    if result is None:
        print("Cannot divide by 0")
    else:
        print(f"Result: {result}")
solution2.pyPython
def is_valid_age(value):
    if not isinstance(value, int):
        return False
    return 0 <= value <= 120

#Test
print(is_valid_age(20))
print(is_valid_age(0))
print(is_valid_age(120))
print(is_valid_age(-1))
print(is_valid_age(150))
print(is_valid_age("abc"))
solution3.pyPython
def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    i = 3
    while i * i <= n:
        if n % i == 0:
            return False
        i += 2
    return True

primes = [n for n in range(1, 51) if is_prime(n)]
print("Prime numbers between 1 and 50:")
print(*primes)

Learn this lesson with a mentor

Work through the Python Series track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now