C
Python/Intro/Lesson 06

Functions

1 hr·theory
This chapter
5/7
Python

Functions

🎯 By the end of this lesson

After finishing this lesson, you will be able to confidently do the following three things.

  • args · *kwargs + the default-value trap (mutable default)
  • ✅ Write type hints + docstrings
  • ✅ First-class functions + closures

Keep the learning goals as a checklist, and close the lesson once you can answer all of them.

8 Function Patterns — Code + Output

A function = a named block of code. It can be reused whenever the same task needs to be performed multiple times.


1. The Simplest Function

python
def greet():
    print("Hello!")

greet()        # Hello!
greet()        # Hello!  (Can be called again)

def (define) → function name → ( ): → indented block.


2. Accepting Parameters

python
def greet(name):
    print(f"Hello {name}!")

greet("Gildong Hong")              # Hello Gildong Hong!
greet("Mongryong Lee")              # Hello Mongryong Lee!

name = parameter (a slot to receive a value). `

💻 greet, add, is_even, default parameters
# ===== Function Definition =====

# Greeting function — Input: name, Output: greeting string
def greet(name):
    return f"Hello, {name}!"

# Addition function — Input: two numbers, Output: sum
def add(a, b):
    return a + b

# Even number determination function — Input: integer, Output: True/False
def is_even(n):
    return n % 2 == 0   # Even if remainder is 0

# Default parameters — Called without arguments uses default values
def introduce(name, age=25, city="Seoul"):
    return f"I am {name}, {age} years old, living in {city}."

# ===== Call and Output =====
print(greet("Hong Gil-dong"))            # Hello, Hong Gil-dong!
print(add(10, 20))                # 30
print(is_even(7))                 # False
print(is_even(8))                 # True

# Using default values
print(introduce("Kim Cheol-su"))        # I am Kim Cheol-su, 25 years old, living in Seoul.
print(introduce("Lee Young-hee", 30, "Busan"))  # I am Lee Young-hee, 30 years old, living in Busan.

# Function without return → returns None
def say_hello():
    print("Hello!")               # Prints, but

result = say_hello()
print(f"Return value: {result}")        # Return value: None

💡 Key Points

1. Parameters with default values must be placed at the end.
2. *args: variable positional arguments (tuple)
3. **kwargs: variable keyword arguments (dictionary)

Python file I/O uses the open() function to open files. The with open(path, mode) as f: pattern guarantees the file is automatically closed. Modes: r (read), w (write), a (append), b (binary). Use json.load/dump for JSON and csv.reader/writer for CSV. pathlib.Path handles file paths in an object-oriented way.

🐍 Try It Out — Functions

Run the concepts above as actual code. The fastest way to learn is to change values and observe the behavior yourself.
✏️ Python 코드
📟 Console output
▶ Press the Run button
🐍 Real Python via Pyodide — first run takes 3–5s to load

🤖 Try Asking AI Like This

Knowing the concepts in this lesson lets you give specific instructions to AI. Instead of a vague "fix this," you can make vocabulary-driven requests — and that is where token savings begin.

  • "Add type hints + a docstring to this function."
  • "Remove the side effects (global variable mutation) from this function and convert it to a pure function."

Why This Reduces Tokens

Without knowing the concepts, you have to ask "What does that mean?" after every AI response. Those follow-up questions consume tokens. Learn the concept once, and the conversation ends in a single exchange.

Defining Functions - Python