Skip to content · ⁨본문 바로가기⁩
Subjects · ⁨과목⁩
  • 1 Getting started · ⁨초기 설정⁩
    1.1

    첫 번째 프로그램

    English

    Python runs your code one line at a time. Each line is a statement 语句. A program 程序 is just a list of statements that run from top to bottom.

    The print() function shows text on the screen. This is called output 输出. Text inside quotes is a string 字符串.

    • Each print() starts a new line.
    • Quotes can be "double" or 'single' — both make a string.
    • A program does nothing until you run it.
    한국어

    Python은 코드를 줄 단위로 순차적으로 실행합니다. 각 줄은 명语句(statement)이며, 프로그램은 위에서 아래로 실행되는 명语句들의 목록일 뿐입니다.

    print() 함수는 화면에 텍스트를 출력합니다. 이를 출력(output)이라고 합니다. 따옴표로 둘러싸인 텍스트는 문자열(string)입니다.

    print("Hello, world!")
    print("I am learning Python")
    
    • 각 print()는 새 줄을 시작합니다.
    • 따옴표는 "double" 또는 'single'일 수 있으며, 둘 다 문자열을 만듭니다.
    • 실행하지 않으면 프로그램은 아무것도 하지 않습니다.
    소스 코드가 인터프리터를 거쳐 출력을 생성함
    소스 코드가 인터프리터를 거쳐 출력을 생성함
    1.2

    주석 및 코드 스타일

    English

    A comment 注释 starts with #. Python ignores everything after the # on that line. Comments explain your code to people; they do not change what the code does.

    Good style makes code easy to read:

    • Use clear names that say what a value means.
    • Put one statement on each line.
    • Do not add spaces at the start of a normal line. In Python, spacing at the start (indentation 缩进) has a special meaning, so a wrong space gives an error 错误.
    한국어

    주석은 #로 시작합니다. Python은 해당 줄의 # 뒤에 오는 모든 것을 무시합니다. 주석은 코드를 사람들에게 설명하기 위한 것이지, 코드의 동작을 변경하지는 않습니다.

    # This line is a note for humans
    print("Hi")        # you can also comment at the end of a line
    

    좋은 스타일은 코드를 읽기 쉽게 만듭니다:

    • 값의 의미를 명확히 나타내는 이름을 사용하세요.
    • 한 줄에 하나의 문장을 작성하세요.
    • 일반 줄의 시작에 공백을 추가하지 마세요. Python에서 시작 부분의 간격(들여쓰기)은 특별한 의미를 가지므로, 잘못된 공백은 오류를 발생시킵니다.
    1.3

    입력, 처리, 출력

    English

    Many programs follow a simple plan: input 输入 → process → output. You get some data, do something with it, then show a result.

    The input() function reads text that the user types. It always gives back a string.

    • input() waits for the user to type and press Enter.
    • Store the typed text in a variable 变量 so you can use it later.
    • Because input() returns a string, change it with int(...) first if you need a number.

    Common mistakes

    • Forgetting the quotes: print(Hello) looks for a variable named Hello and raises a NameError. Text needs quotes: print("Hello").
    • A stray space at the start of a line: Python reads indentation as structure, so it raises an IndentationError.
    • Assuming input() returns a number. It always returns a string, so wrap it in int(...) before doing any maths.
    한국어

    대부분의 프로그램은 간단한 계획에 따릅니다: 입력 → 처리 → 출력. 데이터를 받아서 어떤 작업을 수행한 후 결과를 표시합니다.

    input() 함수는 사용자가 입력한 텍스트를 읽습니다. 항상 문자열을 반환합니다.

    name = input("What is your name? ")
    print("Hello, " + name)
    
    • input()는 사용자가 입력하고 Enter 키를 누를 때까지 대기합니다.
    • 입력한 텍스트를 변수에 저장하여 나중에 사용할 수 있게 하세요.
    • input()가 문자열을 반환하므로, 숫자가 필요한 경우 먼저 int(...)로 변환해야 합니다.

    Common mistakes

    • 따옴표 누락: print(Hello)는 Hello라는 이름의 변수를 찾으려 하여 NameError를 발생시킵니다. 텍스트에는 따옴표가 필요합니다: print("Hello").
    • 줄의 시작 부분에 여분의 공백이 있는 경우: Python은 들여쓰기를 구조로 해석하므로 IndentationError를 발생시킵니다.
    • input()가 숫자를 반환한다고 가정함. 항상 문자열을 반환하므로 수학 연산 전에 int(...)로 감싸야 합니다.
  • 2 Variables, types & operators · ⁨변수, 타입 및 연산자⁩
    2.1

    변수 및 할당

    English

    A variable 变量 is a name for a value 值. You make one with =, which is called assignment 赋值. The name goes on the left; the value goes on the right.

    Now age holds 17. Use the name anywhere you need the value, and change it later:

    • The = sign does not mean "equal". It means "store the right side under the left name".
    • To test if two values are equal, use == (see below).
    한국어

    변수는 값에 붙여 놓은 이름입니다. =를 사용하여 만들며, 이를 할당이라고 부릅니다. 이름은 왼쪽에, 값은 오른쪽에 배치합니다.

    age = 17
    name = "Mei"
    price = 9.99
    print(age, name, price)
    

    이제 age에 17이 저장되었습니다. 값이 필요한 곳에서 이 이름을 사용하고 나중에 변경할 수 있습니다:

    age = 17
    age = age + 1   # age is now 18
    print(age)
    
    변수는 저장된 값에 연결된 이름입니다
    각 변수명은 메모리 상의 값으로 가리킵니다
    • = 기호는 '같다'는 뜻이 아닙니다. '오른쪽을 왼쪽 이름 아래에 저장한다'는 의미입니다.
    • 두 값이 같은지 테스트하려면 ==를 사용하세요(아래 참고).
    2.2

    숫자: int & float

    English

    Python has two main number types. An integer 整数 (int) is a whole number like 17. A float 浮点数 (float) has a decimal point like 9.99.

    These operators 运算符 work on numbers:

    Operator Meaning Example Result
    + add 3 + 2 5
    - subtract 3 - 2 1
    * multiply 3 * 2 6
    / divide (always float) 7 / 2 3.5
    // integer divide 7 // 2 3
    % remainder (modulo) 7 % 2 1
    ** power 2 ** 3 8
    • / always gives a float, so 4 / 2 is 2.0.
    • // and % go together: 17 // 5 is 3, and 17 % 5 is 2.
    한국어

    Python에는 두 가지 주요 숫자 유형이 있습니다. 정수(int, int)는 17와 같은 전체 수입니다. 부동소수점(float, float)는 소수점이 있는 9.99과 같습니다.

    이 연산자는 숫자에 작동합니다:

    연산자 의미 예제 결과
    + 더하기 3 + 2 5
    - 빼기 3 - 2 1
    * 곱하기 3 * 2 6
    / 나누기 (항상 부동소수점) 7 / 2 3.5
    // 정수 나눈 나머지 7 // 2 3
    % 나머지 (모듈로) 7 % 2 1
    ** 제곱 2 ** 3 8
    • /는 항상 부동소수점을 제공하므로, 4 / 2은 2.0입니다.
    • //와 %은 함께 사용됩니다: 17 // 5은 3이며, 17 % 5은 2입니다.
    2.3

    식 및 타입 변환

    English

    An expression 表达式 is anything that has a value, like 3 + 4 * 2. Python uses normal maths order (* and / before + and -); add brackets to make the order clear.

    input() gives a string, so convert it before doing maths. Changing a value from one type to another is type conversion 类型转换:

    • int("abc") fails, so only convert text that looks like a number.
    • Mixing types fails too: "age: " + 17 is an error; write "age: " + str(17).
    한국어

    식(value를 가지는 것)은 3 + 4 * 2와 같습니다. Python은 일반적인 수학 순서를 사용합니다(*과 /이 +과 -보다 먼저); 순서를 명확히 하기 위해 괄호를 추가하세요.

    input()는 문자열을 반환하므로 수학 연산 전에 변환해야 합니다. 값을 한 타입에서 다른 타입으로 바꾸는 것을 타입 변환이라고 합니다:

    age = int("17")        # text "17" -> number 17
    price = float("9.99")  # text -> 9.99
    label = str(17)        # number -> text "17"
    print(age, price, label)
    
    • int("abc")는 실패하므로, 숫자처럼 보이는 텍스트만 변환하세요.
    • 타입을 섞는 것도 실패합니다: "age: " + 17은 오류입니다; "age: " + str(17)을 작성하십시오.
    2.4

    부울린 및 비교

    English

    A Boolean 布尔值 is one of just two values: True or False. A comparison 比较 gives back a Boolean.

    Operator Meaning
    == equal to
    != not equal to
    < > less than / greater than
    <= >= less / greater than or equal to

    Join comparisons with and, or, not:

    Common mistakes

    • / always gives a float, even 4 / 2 is 2.0. Use // when you want a whole number.
    • Using = where you mean ==: = assigns a value, == tests whether two values are equal.
    • Joining a string and a number: "age: " + 5 raises a TypeError. Convert first with str(5).
    • Floats are not exact, so 0.1 + 0.2 is not exactly 0.3 — avoid == on float results.
    한국어

    부울린(Boolean)은 오직 두 가지 값 중 하나인 True 또는 False입니다. 비교 연산은 부울린을 반환합니다.

    연산자 뜻
    == 같다
    != 다르다
    < > 작음 / 큼
    <= >= 작거나 같음 / 크거나 같음
    print(7 > 2)        # True
    print(3 == 3.0)     # True
    age = 20
    print(age >= 18)    # True
    

    비교를 and, or, not으로 연결하세요:

    age = 20
    print(age >= 13 and age <= 19)   # True only for a teenager
    

    Common mistakes

    • /는 항상 부동소수점을 반환하므로, Even if 4 / 2 is 2.0. 정수가 필요한 경우 //을 사용하세요.
    • =을 ==이 필요한 곳에 사용: =은 값을 할당하고, ==은 두 값이 같은지 테스트합니다.
    • 문자열과 숫자를 결합하는 경우: "age: " + 5는 TypeError를 발생시킵니다. 먼저 str(5)로 변환하세요.
    • 부동소수점은 정확하지 않으므로, 0.1 + 0.2는 정확히 0.3이 아닙니다 — 부동소수점 결과에 ==을 피하세요.
  • 3 Strings · ⁨문자열⁩
    3.1

    Indexing

    English

    A string 字符串 is text inside quotes. Each character 字符 has a position, called its index 索引. The first index is 0, not 1.

    Read one character with square brackets:

    • Counting starts at 0, so the last index is len(word) - 1.
    • A negative index counts back from the end: word[-1] is the last character.
    • An index that is too large gives an error 错误 (an IndexError).
    한국어

    A string 字符串 is text inside quotes. Each character 字符 has a position, called its index 索引. The first index is 0, not 1.

    Read one character with square brackets:

    word = "Python"
    print(word[0])    # P  (the first character)
    print(word[2])    # t
    print(len(word))  # 6  (how many characters)
    
    • Counting starts at 0, so the last index is len(word) - 1.
    • A negative index counts back from the end: word[-1] is the last character.
    word = "Python"
    print(word[-1])   # n
    print(word[-2])   # o
    
    • An index that is too large gives an error 错误 (an IndexError).
    s[start:stop] is a half-open window of characters
    s[start:stop] is a half-open window of characters
    3.2

    Slicing

    English

    A slice 切片 takes a part of a string. Write word[start:end]. The slice keeps start but stops before end.

    • Leave out start to begin at 0; leave out end to go to the end.
    • A third number is the step 步长. word[::-1] reverses 反转 the string.
    한국어

    A slice 切片 takes a part of a string. Write word[start:end]. The slice keeps start but stops before end.

    word = "Python"
    print(word[0:3])   # Pyt   (positions 0, 1, 2)
    print(word[2:5])   # tho
    
    • Leave out start to begin at 0; leave out end to go to the end.
    word = "Python"
    print(word[:3])    # Pyt
    print(word[3:])    # hon
    
    • A third number is the step 步长. word[::-1] reverses 反转 the string.
    print("Python"[::-1])   # nohtyP
    
    3.3

    String methods & length

    English

    A method 方法 is a function that belongs to a value. You call it with a dot:

    Strings are immutable 不可变: a method returns a new string and never changes the original 原始 one.

    Common methods (each returns a new value):

    Method Meaning Example Result
    .upper() / .lower() change case "Hi".lower() hi
    .strip() remove edge spaces " hi ".strip() hi
    .replace(a, b) swap text "cat".replace("c", "b") bat
    .split(sep) break into a list "a,b".split(",") ['a', 'b']

    Join strings with +. This is called concatenation 拼接:

    한국어

    A method 方法 is a function that belongs to a value. You call it with a dot:

    name = "mei chen"
    print(name.upper())     # MEI CHEN
    print(name.title())     # Mei Chen
    print(len(name))        # 8
    

    Strings are immutable 不可变: a method returns a new string and never changes the original 原始 one.

    name = "mei"
    print(name.upper())     # MEI  (the returned value)
    print(name)             # mei  (the original is unchanged)
    

    Common methods (each returns a new value):

    Method Meaning Example Result
    .upper() / .lower() change case "Hi".lower() hi
    .strip() remove edge spaces " hi ".strip() hi
    .replace(a, b) swap text "cat".replace("c", "b") bat
    .split(sep) break into a list "a,b".split(",") ['a', 'b']

    Join strings with +. This is called concatenation 拼接:

    first = "Mei"
    last = "Chen"
    print(first + " " + last)   # Mei Chen
    
    3.4

    f-strings

    English

    An f-string 格式化字符串 builds text from values. Put f before the quote, then write {...} around a value.

    • Any expression 表达式 can go inside the braces.
    • {value:.2f} rounds to 2 decimal places 小数位.

    Common mistakes

    • Strings cannot be changed in place: s[0] = "x" raises an error. Build a new string instead.
    • Indexing starts at 0; the last character is s[-1], and s[len(s)] is out of range.
    • A slice s[a:b] includes a but stops before b.
    • String methods return a NEW string: s.upper() does nothing unless you store the result.
    한국어

    An f-string 格式化字符串 builds text from values. Put f before the quote, then write {...} around a value.

    name = "Mei"
    age = 17
    print(f"{name} is {age} years old")   # Mei is 17 years old
    
    • Any expression 表达式 can go inside the braces.
    • {value:.2f} rounds to 2 decimal places 小数位.
    price = 9.5
    print(f"Two cost {price * 2}")        # Two cost 19.0
    print(f"Pi is about {3.14159:.2f}")   # Pi is about 3.14
    

    Common mistakes

    • Strings cannot be changed in place: s[0] = "x" raises an error. Build a new string instead.
    • Indexing starts at 0; the last character is s[-1], and s[len(s)] is out of range.
    • A slice s[a:b] includes a but stops before b.
    • String methods return a NEW string: s.upper() does nothing unless you store the result.
  • 4 Selection · ⁨선택(Selection)⁩
    4.1

    if / elif / else

    English

    A program chooses what to do with if. It runs an indented 缩进 block only when a condition 条件 is true. The if line ends with a colon 冒号.

    Add elif (else-if) for more cases and else for "anything else". Python runs the first true branch 分支 only, then skips the rest.

    • Compare values with == (equal to), != (not equal to), <, >, <=, >=.
    • A comparison 比较 gives a Boolean 布尔值 — either True or False.
    한국어

    프로그램은 if에 대해 무엇을 할지 결정합니다. 조건이 참일 때만 들여쓰기된 블록을 실행합니다. if 줄은 콜론(:)로 끝납니다.

    score = 72
    if score >= 60:
        print("pass")
    # pass
    

    더 많은 경우를 위해 elif(else-if)을 추가하고, "그 외의 모든 것"을 위해 else을 추가하세요. Python은 처음 참인 분기만 실행한 후 나머지는 건너뜁니다.

    score = 72
    if score >= 80:
        print("A")
    elif score >= 60:
        print("B")
    else:
        print("fail")
    # B
    
    • ==(같음), !=(다름), <, >, <=, >=으로 값을 비교하세요.
    • 비교 연산은 부울리(Boolean) 결과를 줍니다—either True 또는 False.
    if / elif / else: 하나의 분기만 실행됨
    if / elif / else: 하나의 분기만 실행됨
    4.2

    조건 결합하기

    English

    Join conditions with and, or, not. and needs both sides true; or needs either side true; not flips a Boolean.

    • Use brackets to make the order clear: (a or b) and c.

    Common mistakes

    • Write elif, not else if.
    • Every if / elif / else line ends with a colon :, and its body must be indented.
    • if x = 5: is an error — use == to compare.
    • else takes no condition; only if and elif do.
    한국어

    조건을 and, or, not으로 연결하세요. and은 양쪽이 참이어야 하고; or은 어느 한쪽이 참이면 되며; not은 부울리를 반전시킵니다.

    age = 16
    has_ticket = True
    if age >= 18 and has_ticket:
        print("entry allowed")
    else:
        print("entry refused")
    # entry refused
    
    • 순서를 명확하게 하기 위해 괄호를 사용하세요: (a or b) and c.
    temp = 30
    if temp > 25 and not temp > 35:
        print("warm but ok")
    # warm but ok
    

    Common mistakes

    • elif을 입력하고, else if은 입력하지 마십시오.
    • 모든 if / elif / else 줄은 콜론 :으로 끝나며, 본체는 들여쓰기되어야 합니다.
    • if x = 5:은 오류입니다. 비교할 때는 ==을 사용하십시오.
    • else은 조건을 받지 않습니다. 조건이 필요한 것은 오직 if과 elif뿐입니다.
  • 5 Iteration · ⁨반복(Iteration)⁩
    5.1

    for loops and range

    English

    A loop 循环 repeats code. A for loop repeats once for each item in a sequence 序列. range(n) gives the numbers 0 up to n - 1.

    • range(a, b) goes from a up to (but not including) b.
    • range(a, b, step) adds a step 步长 each time.
    한국어

    A loop 循环 repeats code. A for loop repeats once for each item in a sequence 序列. range(n) gives the numbers 0 up to n - 1.

    for i in range(5):
        print(i)
    # 0, then 1, 2, 3, 4 (each on its own line)
    
    • range(a, b) goes from a up to (but not including) b.
    • range(a, b, step) adds a step 步长 each time.
    for n in range(2, 11, 2):
        print(n)        # 2 4 6 8 10
    
    for i in range(n): body runs with i = 0 … n-1
    for i in range(n): body runs with i = 0 … n-1
    5.2

    The accumulator pattern

    English

    To build a result across a loop, start a variable before the loop, then update 更新 it each turn. This is the accumulator 累加器 pattern.

    • The same idea counts how many items match a test.
    한국어

    To build a result across a loop, start a variable before the loop, then update 更新 it each turn. This is the accumulator 累加器 pattern.

    total = 0
    for n in range(1, 6):
        total = total + n
    print(total)        # 15
    
    • The same idea counts how many items match a test.
    count = 0
    for letter in "banana":
        if letter == "a":
            count = count + 1
    print(count)        # 3
    
    5.3

    while loops

    English

    A while loop repeats as long as a condition stays true. Change something inside, or it never stops — an infinite loop 无限循环.

    • break leaves the loop straight away.
    한국어

    A while loop repeats as long as a condition stays true. Change something inside, or it never stops — an infinite loop 无限循环.

    n = 1
    while n <= 3:
        print(n)
        n = n + 1
    # 1 2 3
    
    • break leaves the loop straight away.
    total = 0
    while True:
        total = total + 10
        if total >= 30:
            break
    print(total)        # 30
    
    5.4

    Nested loops

    English

    A loop inside another loop is a nested loop 嵌套循环. The inner loop 内层循环 runs fully for each turn of the outer loop 外层循环.

    Common mistakes

    • range(n) goes from 0 to n - 1, not 1 to n — the classic off-by-one error.
    • Changing a list while looping over it skips items; loop over a copy if you must remove things.
    • Forgetting to change the loop variable in a while makes it run forever.
    • Indentation decides what is inside the loop; a wrongly-indented line runs only once, after the loop.
    한국어

    A loop inside another loop is a nested loop 嵌套循环. The inner loop 内层循环 runs fully for each turn of the outer loop 外层循环.

    for row in range(3):
        line = ""
        for col in range(3):
            line = line + "*"
        print(line)
    # ***
    # ***
    # ***
    

    Common mistakes

    • range(n) goes from 0 to n - 1, not 1 to n — the classic off-by-one error.
    • Changing a list while looping over it skips items; loop over a copy if you must remove things.
    • Forgetting to change the loop variable in a while makes it run forever.
    • Indentation decides what is inside the loop; a wrongly-indented line runs only once, after the loop.
  • 6 Lists & 2-D lists · ⁨리스트 및 2D 리스트⁩
    6.1

    Lists

    English

    A list 列表 holds many values in order, inside []. Each item 元素 has an index (from 0).

    • Change an item by its index: scores[1] = 100.
    • A list can grow and shrink; a string cannot.

    The everyday list tools:

    Tool Does
    a.append(x) adds x at the end
    a.insert(i, x) inserts x at position i
    a.remove(x) removes the first x
    a.pop() / a.pop(i) removes and returns the last item / item i
    a.sort() sorts the list in place
    sorted(a) returns a NEW sorted list
    x in a is x in the list?
    len(a), sum(a), max(a), min(a) size and quick maths
    한국어

    A list 列表 holds many values in order, inside []. Each item 元素 has an index (from 0).

    scores = [88, 71, 95]
    print(scores[0])      # 88
    print(len(scores))    # 3
    scores.append(60)     # add to the end
    print(scores)         # [88, 71, 95, 60]
    
    • Change an item by its index: scores[1] = 100.
    • A list can grow and shrink; a string cannot.

    The everyday list tools:

    Tool Does
    a.append(x) adds x at the end
    a.insert(i, x) inserts x at position i
    a.remove(x) removes the first x
    a.pop() / a.pop(i) removes and returns the last item / item i
    a.sort() sorts the list in place
    sorted(a) returns a NEW sorted list
    x in a is x in the list?
    len(a), sum(a), max(a), min(a) size and quick maths
    List indices start at 0
    List indices start at 0
    6.2

    Traversing a list

    English

    To traverse 遍历 a list is to visit each item. A for loop does this with no index needed.

    • Use enumerate when you also need the index.
    한국어

    To traverse 遍历 a list is to visit each item. A for loop does this with no index needed.

    scores = [88, 71, 95]
    total = 0
    for s in scores:
        total = total + s
    print(total)          # 254
    
    • Use enumerate when you also need the index.
    for i, name in enumerate(["a", "b"]):
        print(i, name)    # 0 a  /  1 b
    
    6.3

    2-D lists (grids)

    English

    A 2-D list 二维列表 is a list of lists — a grid 网格 of rows and columns. Use two indexes: grid[row][col].

    • A nested loop 嵌套循环 visits every cell.
    한국어

    A 2-D list 二维列表 is a list of lists — a grid 网格 of rows and columns. Use two indexes: grid[row][col].

    grid = [[1, 2, 3],
            [4, 5, 6]]
    print(grid[0][2])     # 3
    print(grid[1][0])     # 4
    
    • A nested loop 嵌套循环 visits every cell.
    grid = [[1, 2], [3, 4]]
    for row in grid:
        for value in row:
            print(value, end=" ")
    print()               # 1 2 3 4
    
    6.4

    List comprehensions

    English

    A list comprehension 列表推导式 builds a new list in one line: [expression for item in sequence].

    • Add if to keep only some items.
    한국어

    A list comprehension 列表推导式 builds a new list in one line: [expression for item in sequence].

    squares = [x * x for x in range(5)]
    print(squares)        # [0, 1, 4, 9, 16]
    
    • Add if to keep only some items.
    evens = [n for n in range(10) if n % 2 == 0]
    print(evens)          # [0, 2, 4, 6, 8]
    
    6.5

    Tuples & sets

    English

    A tuple 元组 is a fixed sequence in round brackets. It cannot be changed after it is made — use one for values that belong together, and unpack 解包 it into names.

    A function that needs to hand back two results returns a tuple:

    A set 集合 stores each value once, with no order. It is perfect for removing duplicates and for fast membership tests 成员测试.

    Common mistakes

    • b = a does not copy a list: both names point to the same list, so changing one changes the other. Use a.copy() or a[:].
    • The last item is a[-1]; a[len(a)] is out of range.
    • append adds ONE item; use extend or + to join another list.
    • Building a grid with [[0]*3]*3 makes three copies of the same row. Build the rows in a loop instead.
    • A tuple with one item needs a comma: (5,), not (5).
    • A set has no order and no duplicates, so you cannot index it with s[0].
    한국어

    A tuple 元组 is a fixed sequence in round brackets. It cannot be changed after it is made — use one for values that belong together, and unpack 解包 it into names.

    point = (3, 4)
    x, y = point            # unpacking
    print(x, y)             # 3 4
    

    A function that needs to hand back two results returns a tuple:

    def min_max(nums):
        return min(nums), max(nums)
    
    lo, hi = min_max([5, 2, 9])
    print(lo, hi)           # 2 9
    

    A set 集合 stores each value once, with no order. It is perfect for removing duplicates and for fast membership tests 成员测试.

    votes = ["red", "blue", "red", "green", "red"]
    colours = set(votes)
    print(len(colours))         # 3  (duplicates removed)
    print("blue" in colours)    # True
    

    Common mistakes

    • b = a does not copy a list: both names point to the same list, so changing one changes the other. Use a.copy() or a[:].
    • The last item is a[-1]; a[len(a)] is out of range.
    • append adds ONE item; use extend or + to join another list.
    • Building a grid with [[0]*3]*3 makes three copies of the same row. Build the rows in a loop instead.
    • A tuple with one item needs a comma: (5,), not (5).
    • A set has no order and no duplicates, so you cannot index it with s[0].
  • 7 Dictionaries · ⁨딕셔너리⁩
    7.1

    사전

    English

    A dictionary 字典 (dict) stores key 键 → value 值 pairs. You look up a value by its key, not by a number index.

    Add and update

    Assign to a key to add it, or to change an existing one.

    Check and loop

    Use in to test for a key. Loop over the keys, or over .items() to get both key and value.

    • .get(key, default) returns a default 默认值 when the key is missing — no error.

    The classic exam pattern — tally how often each value appears:

    • .get(letter, 0) supplies 0 the first time a key is seen, so there is no KeyError.

    Common mistakes

    • Reading a missing key with d[key] raises a KeyError; use d.get(key) or test if key in d first.
    • Assigning d[key] again overwrites the old value — keys are unique.
    • Keys must be immutable, such as a string or number — a list cannot be a key.
    한국어

    사전(dict)은 키 → 값 쌍을 저장합니다. 숫자 인덱스가 아닌 키를 통해 값을 찾아옵니다.

    student = {"name": "Mei", "score": 88}
    print(student["name"])     # Mei
    print(student["score"])    # 88
    

    추가 및 업데이트

    키에 할당하여 추가하거나 기존 값을 변경할 수 있습니다.

    student = {"name": "Mei"}
    student["score"] = 88      # add a new key
    student["score"] = 90      # update the value
    print(student)             # {'name': 'Mei', 'score': 90}
    

    확인 및 루프

    키 존재 여부를 테스트하려면 in를 사용하십시오. 키를 루프하거나, 키와 값을 모두 얻으려면 .items()을 루프하십시오.

    student = {"name": "Mei", "score": 90}
    print("score" in student)  # True
    for key, value in student.items():
        print(key, "=", value)
    # name = Mei
    # score = 90
    
    • .get(key, default)는 키가 없을 때 기본값을 반환하며, 오류를 발생시키지 않습니다.
    student = {"name": "Mei"}
    print(student.get("age", 0))   # 0
    

    고전적인 시험 유형 — 각 값이 나타나는 횟수를 세어보세요:

    word = "banana"
    counts = {}
    for letter in word:
        counts[letter] = counts.get(letter, 0) + 1
    print(counts)   # {'b': 1, 'a': 3, 'n': 2}
    
    • .get(letter, 0)는 키가 처음 보일 때 0를 제공하므로 KeyError이 발생하지 않습니다.

    Common mistakes

    • d[key]로 없는 키를 읽으려면 KeyError이 발생합니다; d.get(key)를 사용하거나 먼저 if key in d를 확인하십시오.
    • d[key]에 다시 할당하면 기존 값이 덮어씌워집니다. 키는 고유해야 합니다.
    • 키는 불변이어야 하며, 문자열이나 숫자 등입니다. 목록은 키로 사용할 수 없습니다.
    사전(辞典)은 각 키를 하나의 값에 매핑합니다
    사전을 사용하면 각 키를 하나의 값에 매핑할 수 있습니다
  • 8 Functions & abstraction · ⁨함수 및 추상화⁩
    8.1

    Defining & calling functions

    English

    A function 函数 is a named block of code you can reuse. Define 定义 it with def, then call 调用 it by name.

    • The code inside runs only when you call the function.
    한국어

    A function 函数 is a named block of code you can reuse. Define 定义 it with def, then call 调用 it by name.

    def greet():
        print("Hello!")
    
    greet()        # Hello!
    greet()        # Hello!
    
    • The code inside runs only when you call the function.
    def defines; call runs; return sends a value back
    def defines; call runs; return sends a value back
    8.2

    Return values

    English

    A function can return 返回 a value with return. The call then stands for that value.

    • return ends the function at once. A function with no return gives None.
    한국어

    A function can return 返回 a value with return. The call then stands for that value.

    def square(n):
        return n * n
    
    print(square(5))          # 25
    print(square(3) + 1)      # 10
    
    • return ends the function at once. A function with no return gives None.
    8.3

    Parameters, arguments & scope

    English

    A parameter 形参 is the name in the def. An argument 实参 is the value you pass in.

    A variable made inside a function is local 局部 — it exists only there. That region is its scope 作用域.

    A parameter can have a default value 默认值, used when the caller leaves it out:

    한국어

    A parameter 形参 is the name in the def. An argument 实参 is the value you pass in.

    def power(base, exp):         # base, exp are parameters
        return base ** exp
    
    print(power(2, 3))            # 8  (2 and 3 are arguments)
    

    A variable made inside a function is local 局部 — it exists only there. That region is its scope 作用域.

    def f():
        x = 10            # local to f
        return x
    
    print(f())            # 10
    # print(x) here would be an error: x is not defined outside f
    

    A parameter can have a default value 默认值, used when the caller leaves it out:

    def greet(name, greeting="Hello"):
        return greeting + ", " + name
    
    print(greet("Mei"))              # Hello, Mei
    print(greet("Sam", "Welcome"))   # Welcome, Sam
    
    8.4

    Procedural abstraction

    English

    Procedural abstraction 过程抽象 means hiding details behind a name. You use a function by its name and what it does, not by how it works.

    • A good function does one job, has a clear name, and avoids repeating code.
    한국어

    Procedural abstraction 过程抽象 means hiding details behind a name. You use a function by its name and what it does, not by how it works.

    def area_of_rectangle(w, h):
        return w * h
    
    print(area_of_rectangle(4, 5))   # 20
    
    • A good function does one job, has a clear name, and avoids repeating code.
    8.5

    Modules & imports

    English

    A module 模块 is a file of ready-made functions. Bring one in with import 导入.

    Common mistakes

    • A function returns None unless you write return. Printing is not the same as returning.
    • Never use a mutable default like def f(x=[]) — the same list is shared between all calls.
    • A variable made inside a function is local and cannot be seen outside it.
    • Run a function with f(); writing f on its own only names it.
    한국어

    A module 模块 is a file of ready-made functions. Bring one in with import 导入.

    import random
    random.seed(0)               # makes the result repeatable
    print(random.randint(1, 6))  # a dice roll
    
    import math
    print(math.sqrt(16))         # 4.0
    

    Common mistakes

    • A function returns None unless you write return. Printing is not the same as returning.
    • Never use a mutable default like def f(x=[]) — the same list is shared between all calls.
    • A variable made inside a function is local and cannot be seen outside it.
    • Run a function with f(); writing f on its own only names it.
  • 9 Errors, exceptions & testing · ⁨오류, 예외 및 테스트⁩
    9.1

    오류 & 디버깅

    English

    Code can fail in three ways. A syntax error 语法错误 breaks Python's rules, so it never runs. A runtime error 运行时错误 happens while running, like dividing by zero. A logic error 逻辑错误 runs but gives the wrong answer.

    • Python prints a traceback 回溯 showing where it failed. Read it from the bottom up.
    한국어

    코드는 세 가지 방식으로 실패할 수 있습니다. 구문 오류(syntax error)는 Python 규칙을 위반하여 실행되지 않습니다. 런타임 오류(runtime error)는 실행 중 발생하며, 0으로 나누기 등이 포함됩니다. 논리 오류(logic error)는 실행되지만 잘못된 결과를 줍니다.

    # A runtime error, caught so this block still finishes:
    try:
        print(10 / 0)
    except ZeroDivisionError:
        print("cannot divide by zero")
    # cannot divide by zero
    
    • Python은 실패 위치를 보여주는 traceback을 출력합니다. 아래에서 위로 읽어보십시오.
    Common Python errors: Syntax, Name, Type, Index
    Common Python errors: Syntax, Name, Type, Index
    9.2

    try / except / raise

    English

    Wrap risky code in try. If it fails, except catches the exception 异常 and handles 处理 it, instead of crashing.

    • Catch a specific type (ValueError, ZeroDivisionError, …).
    • raise makes your own error on purpose.
    한국어

    위험한 코드를 try으로 감쌉니다. 실패하면 except이 예외를.catch하여 충돌하지 않고 처리합니다.

    def to_int(text):
        try:
            return int(text)
        except ValueError:
            return 0
    
    print(to_int("42"))    # 42
    print(to_int("abc"))   # 0
    
    • 특정 타입의 예외를 catch합니다 (ValueError, ZeroDivisionError 등).
    • raise은 의도적으로 사용자 정의 오류를 발생시킵니다.
    def set_age(age):
        if age < 0:
            raise ValueError("age cannot be negative")
        return age
    
    try:
        set_age(-1)
    except ValueError as err:
        print("error:", err)
    # error: age cannot be negative
    
    9.3

    테스트 & 내구성

    English

    A test 测试 checks that code gives the right answer. Try normal cases and edge cases 边界情形 — empty input, zero, very large values.

    • Robust 健壮 code does not crash on strange input; it handles it gracefully.

    Common mistakes

    • Do not use a bare except: — catch the specific error, e.g. except ValueError:.
    • A syntax error stops the whole program before it runs, so fix those first.
    • Test the edge cases (empty input, zero, the largest value), not just the easy one.
    한국어

    테스트는 코드가 올바른 결과를 내놓는지 확인합니다. 정상적인 경우 와 가장자리(case edge case) — 빈 입력, 0, 매우 큰 값 — 모두 시도하십시오.

    def average(nums):
        if len(nums) == 0:        # edge case: empty list
            return 0
        return sum(nums) / len(nums)
    
    print(average([2, 4, 6]))     # 4.0
    print(average([]))            # 0
    
    • 내구성이 높은 코드는 이상한 입력에도 충돌하지 않으며, 이를 우아하게 처리합니다.

    Common mistakes

    • bare except:을 사용하지 마십시오. 구체적인 오류를 catch하십시오. 예: except ValueError:.
    • 구문 오류는 실행 전에 전체 프로그램을 멈추므로 먼저 수정하십시오.
    • 쉬운 경우뿐만 아니라 가장자리ケース(edge cases) — 빈 입력, 0, 최대 값 —도 테스트하십시오.
  • 10 Files · ⁨파일(File)⁩
    10.1

    텍스트 파일 읽기 및 쓰기

    English

    A text file 文本文件 stores text on disk. Open it with open(name, mode) where mode 模式 says read or write. Always use with, which closes the file for you.

    Writing

    Mode "w" writes a new file and erases any old one.

    Reading

    Mode "r" (the default) reads. .read() returns the whole file as one string.

    Line by line

    Loop over the file to get one line at a time. .strip() removes 去除 the newline 换行符 at the end.

    Appending

    Mode "a" appends 追加 — it adds to the end without erasing.

    Mode Meaning
    "r" read (default)
    "w" write (erases first)
    "a" append (add to the end)

    Common mistakes

    • Always close a file, or use with open(...) as f: which closes it for you.
    • read() gives the whole file as one string, and each line still ends with \n.
    • Opening with "w" erases the file first; use "a" to add to the end.
    한국어

    텍스트 파일은 디스크에 텍스트를 저장합니다. mode가 read 또는 write일 때 open(name, mode)으로 엽니다. 항상 with을 사용하십시오. 이는 파일을 자동으로 닫아줍니다.

    쓰기

    모드 "w"는 새 파일을 작성하며 기존 파일은 지워집니다.

    with open("notes.txt", "w") as f:
        f.write("first line\n")
        f.write("second line\n")
    print("saved")            # saved
    

    읽기

    mode "r"(기본값)은 읽습니다. .read()은 전체 파일을 하나의 문자열로 반환합니다.

    with open("notes.txt", "w") as f:
        f.write("hello\nworld\n")
    with open("notes.txt") as f:
        print(f.read().strip())   # hello / world
    

    줄 단위로

    파일 루프를 돌면서 한 줄씩 얻습니다. .strip()은末尾의 줄바꿈을 제거합니다.

    with open("data.txt", "w") as f:
        f.write("Mei,88\nSam,71\n")
    with open("data.txt") as f:
        for line in f:
            name, score = line.strip().split(",")
            print(name, "scored", score)
    # Mei scored 88
    # Sam scored 71
    

    추가하기

    mode "a"은 추가합니다 — 삭제 없이末尾에追加합니다.

    with open("log.txt", "w") as f:
        f.write("line 1\n")
    with open("log.txt", "a") as f:
        f.write("line 2\n")
    with open("log.txt") as f:
        print(f.read().strip())   # line 1 / line 2
    
    Mode Meaning
    "r" read (default)
    "w" write (erases first)
    "a" append (add to the end)

    Common mistakes

    • 항상 파일을 닫거나, with open(...) as f:을 사용하여 자동으로 닫게 하십시오.
    • read()은 전체 파일을 하나의 문자열로 제공하며, 각 줄은 여전히 \n으로 끝납니다.
    • "w"으로 열면 먼저 파일을 삭제하므로,末尾에 추가하려면 "a"을 사용하십시오.
    open → read/write → close (with auto-closes)
    open → read/write → close (with auto-closes)
  • 11 Algorithm design · ⁨알고리즘 설계(Algorithm design)⁩
    11.1

    알고리즘 & 분해

    English

    An algorithm 算法 is a clear list of steps that solves a problem. Decomposition 分解 means breaking a big problem into smaller parts you can solve one at a time.

    • Abstraction 抽象 means ignoring detail: you use largest(...) without re-reading how it works.
    한국어

    알고리즘은 문제를 해결하는 명확한 단계 목록입니다. 분해(decomposition)는 큰 문제를 작은 부분으로 나누어 하나씩 해결할 수 있게 하는 것입니다.

    # Algorithm: find the largest number in a list
    def largest(nums):
        best = nums[0]
        for n in nums:
            if n > best:
                best = n
        return best
    
    print(largest([3, 9, 2, 7]))   # 9
    
    • 추상화는 세부 사항을 무시하는 것입니다. largest(...)을 어떻게 작동하는지 다시 읽지 않고 사용합니다.
    11.2

    가상의 코드 & 흐름도

    English

    Pseudocode 伪代码 is plain, structured English for an algorithm, written before the real code. It is not run.

    A flowchart 流程图 draws the same plan: a box for each step, a diamond for each decision 判断, and arrows for the order.

    한국어

    가상의 코드는 실제 코드 이전에 작성되는 알고리즘을 위한plain, 구조화된 영어입니다. 실행되지 않습니다.

    SET best TO first number
    FOR Each number n
        IF n > best
          THEN
            SET best TO n
            OUTPUT best
    

    흐름도는 동일한 계획을그립니다: 각 단계마다 상자, 각 결정마다 마름모, 순서에 따라 화살표를 사용합니다.

    11.3

    재귀 & 호출 택

    English

    Recursion 递归 is when a function calls itself. It needs a base case 基准情形 (a simple input that returns at once) and a recursive case 递归情形 (it calls itself on a smaller input).

    • Each paused call sits on the call stack 调用栈 until the call above it returns.

    Common mistakes

    • Recursion needs a base case, or it calls itself forever and crashes the call stack.
    • Pseudocode is for planning — it need not run, but every step must be unambiguous.
    • Break a big problem into small named steps before you write any code.
    한국어

    재귀는 함수가 자신을 호출하는 것입니다. 기본 케이스(base case, 간단한 입력이 즉시 반환)와 재귀적 경우(recursive case, 더 작은 입력에서 자신을 호출)가 필요합니다.

    factorial(3)의 콜 스택: 각 호출이 대기했다가 역순으로 반환
    factorial(3)의 콜 스택: 각 호출이 대기했다가 역순으로 반환
    def fact(n):
        return 1 if n <= 1 else n * fact(n - 1)
    
    print(fact(5))     # 120
    
    • each paused call sits on the call stack until the call above it returns.

    Common mistakes

    • 재귀에는 기본 케이스가 필요하며, 그렇지 않으면 무한히 자신을 호출하여 호출 스택이 충돌합니다.
    • 가상의 코드는 계획용입니다. 실행될 필요는 없지만, 모든 단계는 모호하지 않아야 합니다.
    • 코드를 작성하기 전에 큰 문제를 작은 이름 붙은 단계로 나누십시오.
  • 12 Data structures · ⁨데이터 구조⁩
    12.1

    추상 데이터 타입(ADT)

    English

    An abstract data type 抽象数据类型 (ADT) describes some data plus the operations on it, separate from how it is built. You use it through its operations, not through its inner storage.

    한국어

    추상 데이터 유형(ADT)은 데이터와 그에 대한 연산을 설명하며, 구현 방식과는 분리됩니다. 내부 저장소가 아닌 연산을 통해 사용합니다.

    # A stack ADT, built on a list
    s = []
    s.append(1)        # add
    s.append(2)
    print(s.pop())     # 2  (remove the most recent)
    
    12.2

    스택

    English

    A stack 栈 is last-in, first-out (LIFO 后进先出). You push 压入 onto the top and pop 弹出 from the top.

    한국어

    스택은 Last-In, First-Out(LIFO)입니다. top에 push하고 top에서 pop합니다.

    스택은 상단에서 제거(LIFO); 큐는 앞쪽에서 제거(FIFO)
    스택은 상단에서 제거(LIFO); 큐는 앞쪽에서 제거(FIFO)
    stack = []
    stack.append("a")
    stack.append("b")
    print(stack.pop())   # b
    print(stack.pop())   # a
    
    12.3

    큐

    English

    A queue 队列 is first-in, first-out (FIFO 先进先出). You enqueue 入队 at the back and dequeue 出队 from the front.

    한국어

    큐는 First-In, First-Out(FIFO)입니다. back에서 enqueue하고 front에서 dequeue합니다.

    queue = []
    queue.append("a")     # enqueue
    queue.append("b")
    print(queue.pop(0))   # a  (dequeue the front)
    print(queue.pop(0))   # b
    
    12.4

    링크드 리스트

    English

    A linked list 链表 is a chain of nodes 节点. Each node holds data and a pointer 指针 to the next node; the last points to None.

    한국어

    연결 목록(linked list)은 노드들의 사슬입니다. 각 노드는 데이터와 다음 노드에 대한 포인터를 가지며, 마지막 노드는 None을 가리킵니다.

    연결リスト: 각 노드가 데이터와 다음 노드를 가리키는 포인터를 포함하며 None으로 끝납니다
    연결리스트: 각 노드가 데이터와 다음 노드를 가리키는 포인터를 포함하며 None으로 끝납니다
    n3 = {"data": 3, "next": None}
    n2 = {"data": 2, "next": n3}
    n1 = {"data": 1, "next": n2}
    node = n1
    while node is not None:      # traverse to the end
        print(node["data"])
        node = node["next"]
    # 1 2 3
    
    12.5

    해시 테이블

    English

    A hash table 哈希表 maps a key to a slot with a hash function 哈希函数. Two keys can land in the same slot — a collision 冲突. Python's dict is a hash table, so lookup is fast.

    한국어

    해시 테이블은 해시 함수를 사용하여 키를 슬롯에 매핑합니다. 두 키가 같은 슬롯에 배치될 수 있는데, 이를 충돌(collision)이라고 합니다. Python의 dict은 해시 테이블이므로 검색이 빠릅니다.

    해시 함수는 각 키를 슬롯에 매핑하며, 두 개의 키가 하나의 슬롯에서 충돌할 수 있습니다
    해시 함수는 각 키를 슬롯에 매핑합니다. 두 개의 키가 하나의 슬롯에서 충돌할 수 있습니다
    table = {}
    table["Mei"] = 88
    table["Sam"] = 71
    print(table["Mei"])   # 88  (fast lookup by key)
    
    12.6

    이진 탐색 트리

    English

    A binary search tree 二叉搜索树 (BST) keeps order: every left child is smaller than its node, every right child is larger. Search stays fast.

    한국어

    이진 탐색 트리(BST)는 순서를 유지합니다: 모든 왼쪽 자식 노드는 부모보다 작고, 모든 오른쪽 자식 노드는 부모보다 니다. 검색 속도가 빠릅니다.

    이진 탐색 트리: 작은 값은 왼쪽으로, 큰 값은 오른쪽으로 배치됩니다
    이진 탐색 트리: 작은 값은 왼쪽으로, 큰 값은 오른쪽으로 배치됩니다
    def insert(root, val):
        if root is None:
            return {"val": val, "left": None, "right": None}
        if val < root["val"]:
            root["left"] = insert(root["left"], val)
        else:
            root["right"] = insert(root["right"], val)
        return root
    
    def inorder(root):
        if root is None:
            return []
        return inorder(root["left"]) + [root["val"]] + inorder(root["right"])
    
    tree = None
    for v in [5, 3, 8, 1, 4]:
        tree = insert(tree, v)
    print(inorder(tree))   # [1, 3, 4, 5, 8]
    
    12.7

    그래프

    English

    A graph 图 is a set of vertices 顶点 joined by edges 边. An adjacency list 邻接表 — a dict of neighbour lists — is a common way to store one.

    Common mistakes

    • A stack is last-in-first-out; a queue is first-in-first-out. Do not mix them up.
    • Check whether a structure is empty before you pop or dequeue from it.
    • In a linked list, losing the head pointer loses the whole list.
    한국어

    그래프는 엣지(연결선)로 연결된 정점의 집합입니다. 인접 목록 — 이웃 목록을 저장하는 사전 데이터 구조 —은 이를 저장하는 일반적인 방법입니다.

    정점과 엣지로 구성된 그래프 및 그 인접 목록 형태
    정점과 엣지로 구성된 그래프 및 그 인접 목록 형태
    graph = {"A": ["B", "D"], "B": ["A", "C"], "C": ["B", "D"], "D": ["A", "C"]}
    for vertex in graph:
        print(vertex, "->", graph[vertex])
    # A -> ['B', 'D']  (and so on for B, C, D)
    

    Common mistakes

    • 스택은 Last-In-First-Out(LIFO), 큐는 First-In-First-Out(FIFO)입니다. 혼동하지 마십시오.
    • 스택이나 큐에서 값을 제거(popping/dequeuing)하기 전에 구조체가 비어 있는지 확인하십시오.
    • 링크드 리스트에서 head 포인터를 잃으면 전체 리스트를 잃게 됩니다.
  • 13 Searching, sorting & efficiency · ⁨검색, 정렬 및 효율성⁩
    13.1

    선형 탐색 및 이진 탐색

    English

    A search 查找 finds where a value is. Linear search 线性查找 checks each item in turn, so it works on any list.

    Binary search 二分查找 is much faster but needs a sorted list. It halves the range each step.

    한국어

    검색은 값이 어디에 있는지 찾습니다. 선형 검색은 항목을 순차적으로 확인하므로 어떤 리스트에서도 작동합니다.

    def linear_search(items, target):
        for i in range(len(items)):
            if items[i] == target:
                return i
        return -1     # not found
    
    print(linear_search([4, 8, 2, 9], 2))   # 2
    

    이진 검색은 훨씬 빠르지만 정렬된 리스트가 필요합니다. 각 단계마다 범위를 절반으로 줄입니다.

    def binary_search(items, target):
        lo, hi = 0, len(items) - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if items[mid] == target:
                return mid
            elif items[mid] < target:
                lo = mid + 1
            else:
                hi = mid - 1
        return -1
    
    print(binary_search([1, 3, 5, 7, 9], 7))   # 3
    
    이진 검색은 각 단계마다 범위를 절반으로 줄임 — 정렬된 리스트에서 O(log n)
    이진 검색은 각 단계마다 범위를 절반으로 줄임 — 정렬된 리스트에서 O(log n)
    13.2

    정렬 (버블 & 삽입)

    English

    To sort 排序 is to put items in order. Bubble sort 冒泡排序 repeatedly swaps 交换 neighbours that are in the wrong order.

    Insertion sort 插入排序 builds a sorted part one item at a time, sliding each new item back into its place:

    • In real code, use Python's built-in sorted():
    한국어

    정렬은 항목을 순서대로 나열하는 것입니다. 버블 정렬은 잘못된 순서의 인접한 항목을 반복해서 스왑합니다.

    def bubble_sort(a):
        a = a[:]                          # work on a copy
        for i in range(len(a)):
            for j in range(len(a) - 1 - i):
                if a[j] > a[j + 1]:
                    a[j], a[j + 1] = a[j + 1], a[j]
        return a
    
    print(bubble_sort([5, 2, 4, 1]))      # [1, 2, 4, 5]
    

    삽입 정렬은 정렬된 부분을 하나씩 구축하며, 새로운 항목을 제자리에 밀어 넣습니다:

    def insertion_sort(a):
        a = a[:]                           # work on a copy
        for i in range(1, len(a)):
            key = a[i]
            j = i - 1
            while j >= 0 and a[j] > key:   # shift bigger values right
                a[j + 1] = a[j]
                j -= 1
            a[j + 1] = key                 # drop key into the gap
        return a
    
    print(insertion_sort([5, 2, 4, 1]))   # [1, 2, 4, 5]
    
    • 실제 코드에서는 Python의 내장 sorted()을 사용하십시오:
    print(sorted([5, 2, 4, 1]))           # [1, 2, 4, 5]
    
    13.3

    알고리즘 효율성

    English

    Efficiency 效率 asks how the work grows as the input grows. We describe it with Big-O 大O记号.

    Big-O Name Example
    $O(1)$ constant look up a dict key
    $O(\log n)$ logarithmic binary search
    $O(n)$ linear linear search
    $O(n^2)$ quadratic bubble sort
    한국어

    효율성은 입력 크기가 커질 때 작업량이 어떻게 증가하는지를 묻습니다. Big-O notation으로 설명합니다.

    일반적인 복잡도별 입력 크기 대비 단계 수 증가 추이
    일반적인 복잡도별 입력 크기 대비 단계 수 증가 추이
    Big-O 이름 예시
    $O(1)$ 상수 사전 데이터 구조의 키 조회
    $O(\log n)$ 로그arithmic 이진 검색
    $O(n)$ 선형 선형 검색
    $O(n^2)$ 이차 버블 정렬
    def steps(n):           # how many steps a linear scan takes
        count = 0
        for i in range(n):
            count = count + 1
        return count
    
    print(steps(100))       # 100  -> O(n)
    
    13.4

    무작위성 및 시뮬레이션

    English

    The random module makes random numbers. Use a seed 种子 to make results repeatable. A simulation 模拟 runs many random trials to estimate an answer.

    Common mistakes

    • Binary search only works on a sorted list.
    • Big-O tells you how the time GROWS, not the exact time; an O(n²) method beats O(n) only for tiny inputs.
    • Bubble sort is O(n²) — fine for learning, but slow on large lists.
    한국어

    random 모듈은 무작위 숫자를 생성합니다. 결과를 재현 가능하게 하기 위해 시드(seed)를 사용하십시오. 시뮬레이션은 많은 무작위 시련(trial)을 수행하여 답을 추정합니다.

    import random
    random.seed(0)
    rolls = [random.randint(1, 6) for _ in range(1000)]
    print(rolls.count(6))   # about 1/6 of 1000
    

    Common mistakes

    • 이진 검색은 오직 정렬된 리스트에서만 작동합니다.
    • Big-O는 시간이 어떻게 '증가'하는지를 알려주며, 정확한 시간을 의미하지 않습니다. O(n²) 방식이 O(n) 방식보다 빠른 것은 매우 작은 입력일 때に限정됩니다.
    • 버블 정렬은 O(n²) — 학습용으로는 적절하지만, 큰 리스트에서는 느립니다.
  • 14 OOP & paradigms · ⁨OOP 및 패러다임⁩
    14.1

    클래스 및 객체

    English

    A class 类 is a blueprint. An object 对象 is one thing built from it (an instance 实例). __init__ is the constructor 构造方法 that sets up each object; self is the object itself.

    • name is an attribute 属性 (data on the object); speak is a method 方法 (an action).

    Add __str__ to control what print(obj) shows:

    한국어

    클래스는 설계도(blueprint)입니다. 객체는 이를 기반으로 만들어진 하나의实例(instantiation)입니다. __init__은 각 객체를 설정하는 컨스트럭터(constructor)이며, self은 객체 자체입니다.

    class Dog:
        def __init__(self, name):
            self.name = name            # an attribute
        def speak(self):
            return self.name + " says woof"
    
    d = Dog("Rex")
    print(d.speak())     # Rex says woof
    
    • name은 속성(attribute, 객체의 데이터)이고, speak은 메소드(method, 행동)입니다.

    __str__을 추가하여 print(obj)이 표시하는 내용을 제어하세요:

    class Dog:
        def __init__(self, name):
            self.name = name
        def __str__(self):
            return f"Dog named {self.name}"
    
    print(Dog("Rex"))    # Dog named Rex
    
    클래스는 설계도이며, 이를 호출하면 객체가 생성됩니다
    클래스는 설계도이며, 이를 호출하면 객체가 생성됩니다
    14.2

    상속, 캡슐링 및 다态性(Polymorphism)

    English

    Inheritance 继承 lets a subclass 子类 reuse a superclass 父类. Use super() to call the parent; override 重写 a method to change it.

    Encapsulation 封装 hides data behind methods; a leading underscore marks it private 私有.

    Polymorphism 多态 means one name, many behaviours — the right speak runs for each object.

    한국어

    상속(subclass)은 superclass의 기능을 재사용할 수 있게 합니다. parent를 호출하려면 super()을 사용하고, 메소드를 오라이드(override)하여 변경할 수 있습니다.

    class Animal:
        def speak(self):
            return "some sound"
    
    class Cat(Animal):
        def speak(self):                # override
            return "meow"
    
    print(Cat().speak())   # meow
    

    캡슐링은 데이터를 메소드 뒤에 숨깁니다. 앞쪽에 언더스코어(_)가 붙으면_private_으로 표시됩니다.

    class Account:
        def __init__(self):
            self._balance = 0           # private
        def deposit(self, n):
            self._balance += n
        def balance(self):
            return self._balance
    
    a = Account()
    a.deposit(50)
    print(a.balance())     # 50
    

    다态性(polymorphism)는 동일한 이름으로 다양한 행동을 의미하며, 각 객체에 맞는 올바른 speak이 실행됩니다.

    class Cat:
        def speak(self):
            return "meow"
    
    class Cow:
        def speak(self):
            return "moo"
    
    for animal in [Cat(), Cow()]:
        print(animal.speak())   # meow, then moo
    
    14.3

    프로그래밍 패러다임

    English

    A paradigm 范式 is a style of writing programs. Procedural 过程式 code is a sequence of steps and functions. Object-oriented 面向对象 code groups data and methods into objects. Declarative 声明式 code says what you want, not how (a list comprehension or SQL).

    Common mistakes

    • Every method needs self as its first parameter.
    • __init__ sets up a new object and runs automatically when you create one.
    • Two objects of the same class have separate attributes; changing one does not change the other.
    한국어

    파라다임(paradigm)은 프로그래밍 스타일입니다. 프로세듀럴 코드는 단계와 함수의 연속입니다. 객체 지향 코드는 데이터와 메소드를 객체로 묶습니다. 선언적(declarative) 코드는 '어떻게'가 아니라 **'무엇'**을 원하는지 명시합니다(예: 리스트 컴프리헨션 또는 SQL).

    def total(nums):           # procedural
        t = 0
        for n in nums:
            t += n
        return t
    print(total([1, 2, 3]))    # 6
    
    print(sum([1, 2, 3]))      # 6  (declarative: same result)
    

    Common mistakes

    • 모든 메서드는 첫 번째 매개변수로 self을 필요로 합니다.
    • __init__은 새 객체를 설정하고, 객체를 생성할 때 자동으로 실행됩니다.
    • 같은 클래스의 두 객체는 독립적인 속성을 가집니다.其中一个의 변경은 다른 쪽에 영향을 주지 않습니다.
  • 15 Data representation · ⁨데이터 표현⁩
    15.1

    Bits & binary

    English

    A bit 比特 is a single 0 or 1. Binary 二进制 is the base-2 number system: each place is worth twice the one to its right (1, 2, 4, 8, …). Denary 十进制 (base-10) is our normal numbers.

    • 8 bits make a byte 字节. A fixed width can overflow 溢出 (wrap around) when the number is too big.

    Hexadecimal 十六进制 (base 16) is a compact way to read binary: one hex digit stands for exactly four bits. Python writes hex with 0x:

    한국어

    A bit 比特 is a single 0 or 1. Binary 二进制 is the base-2 number system: each place is worth twice the one to its right (1, 2, 4, 8, …). Denary 十进制 (base-10) is our normal numbers.

    Binary place values: 1101 means 8 + 4 + 1 = 13
    Binary place values: 1101 means 8 + 4 + 1 = 13
    print(bin(13))         # 0b1101
    print(int("1101", 2))  # 13
    
    • 8 bits make a byte 字节. A fixed width can overflow 溢出 (wrap around) when the number is too big.
    x = 250
    x = (x + 10) % 256     # one byte wraps at 256
    print(x)               # 4
    

    Hexadecimal 十六进制 (base 16) is a compact way to read binary: one hex digit stands for exactly four bits. Python writes hex with 0x:

    print(hex(255))        # 0xff
    print(0xFF)            # 255
    print(int("ff", 16))   # 255
    
    15.2

    Compression

    English

    Compression 压缩 makes data smaller. Lossless 无损 compression keeps every bit, so you rebuild the original exactly. Lossy 有损 compression throws away detail — smaller but not exact — and is used for photos and music.

    Run-length encoding 游程编码 is a simple lossless method: store a run 游程 (a repeat) as a count plus the value.

    Common mistakes

    • n bits store 2**n different values, from 0 up to 2**n - 1.
    • Lossy compression throws away detail and cannot be undone; lossless can be reversed exactly.
    한국어

    Compression 压缩 makes data smaller. Lossless 无损 compression keeps every bit, so you rebuild the original exactly. Lossy 有损 compression throws away detail — smaller but not exact — and is used for photos and music.

    Run-length encoding 游程编码 is a simple lossless method: store a run 游程 (a repeat) as a count plus the value.

    def rle(text):
        out = ""
        i = 0
        while i < len(text):
            run = 1
            while i + run < len(text) and text[i + run] == text[i]:
                run += 1
            out += str(run) + text[i]
            i += run
        return out
    
    print(rle("AAAABBBCCD"))   # 4A3B2C1D
    

    Common mistakes

    • n bits store 2**n different values, from 0 up to 2**n - 1.
    • Lossy compression throws away detail and cannot be undone; lossless can be reversed exactly.
  • 16 Computing concepts · ⁨컴퓨팅 개념⁩
    16.1

    컴퓨팅의 정의 및 디자인 사이클

    English

    Computing 计算 means solving problems with computers: input, process, output. Good software is built in a design cycle 设计循环 — plan, write, test, improve — repeated many times.

    • Break a problem down, build a small part, test it, then add more.
    • Programmers work in teams and reuse each other's code.
    한국어

    컴퓨팅은 컴퓨터를 사용하여 문제를 해결하는 것: 입력, 처리, 출력. 좋은 소프트웨어는 디자인 사이클(계획, 작성, 테스트, 개선)을 여러 번 반복하여 구축됩니다.

    • 문제를 분해하고, 작은 부분을 만들고, 테스트한 후 더 추가하십시오.
    • 프로그래머는 팀으로 협력하며 서로의 코드를 재사용합니다.
    16.2

    인터넷(Internet)

    English

    The Internet 互联网 is a network 网络 of networks. Data is split into packets 数据包 that travel separately and are put back together at the other end. Shared rules called protocols 协议 (such as TCP/IP) make this work. If one path breaks, packets take another route — this is redundancy 冗余, which gives fault tolerance 容错.

    Layer Job
    HTTP request and send web pages
    TCP reliable delivery, in order
    IP addressing and routing
    한국어

    인터넷은 네트워크들의 네트워크입니다. 데이터는 패킷(packet)으로 분리되어 개별적으로 전송되며, 수신 측에서 다시 합쳐집니다. TCP/IP와 같은 프로토콜(protocol)이라는 공유 규칙이 이를 가능하게 합니다. 한 경로가 끊어지면 패킷은 다른 경로를 이용합니다 — 이는 리던던시(redundancy)이며, Fault tolerance(내결함성)를 제공합니다.

    인터넷 지도: 각 선은 두 네트워크 간의 경로입니다
    인터넷 지도: 각 선은 두 네트워크 간의 경로입니다
    레이어 역할
    HTTP 웹 페이지 요청 및 전송
    TCP 신뢰 가능한 전달, 순서 보장
    IP 주소 지정 및 라우팅
    16.3

    병렬 및 분산 컴퓨팅

    English

    Sequential 顺序 code does one step at a time. Parallel 并行 computing does several steps at once on many cores 核心, which can give a speedup 加速. Distributed 分布式 computing spreads the work across many computers, such as a cloud.

    • Not everything can run in parallel: some steps must wait for an earlier result.
    한국어

    순차적 코드는 한 단계씩 수행합니다. 병렬 컴퓨팅은 여러 코어에서 여러 단계를 동시에 수행하여 속도를 높일 수 있습니다. 분산 컴퓨팅은 클라우드와 같은 여러 컴퓨터에 작업을 분산시킵니다.

    • 모든 것이 병렬로 실행되는 것은 아닙니다: 일부 단계는 이전 결과의 처리를 기다려야 합니다.
    16.4

    컴퓨팅의 영향

    English

    Computing brings both benefits and harms. The digital divide 数字鸿沟 means not everyone has equal access to it. Software can carry bias 偏见 from the data it learns from. Respect intellectual property 知识产权 (licences), and protect people's personal data 个人数据 and privacy 隐私.

    Common mistakes

    • The Internet and the World Wide Web are not the same: the Web is one service that runs on top of the Internet.
    • More processor cores help only if the work can be split into parts that run at the same time.
    한국어

    컴퓨팅은 이점과 해로운 측면을 모두 가집니다. 디지털 격차는 모든 사람이 동등하게 접근할 수 있음을 의미하지 않습니다. 소프트웨어는 학습하는 데이터로부터 편향을 포함할 수 있습니다. 지적 재산권(라이선스)을 존중하고, 사람들의 개인정보 및 프라이버시를 보호하십시오.

    Common mistakes

    • 인터넷과 월드 와이드 웹은 다릅니다: 웹은 인터넷 위에서 작동하는 하나의 서비스입니다.
    • 더 많은 프로세서 코어가 도움이 되려면 작업이 동시에 실행되는 부분으로 나뉠 수 있어야 합니다.
  • 17 Putting it together · ⁨모아보기⁩
    17.1

    엔드 투 엔드 미니 프로젝트

    English

    A mini-project 小项目 combines earlier ideas: data in a list, a function with selection inside a loop, and printed output. This is also the shape of the AP Create Performance Task.

    Project: average mark

    Project: count passes

    Project: filter to a new list

    The AP Create Task wants a list, a parameterised procedure 过程 that uses selection 选择 and iteration 迭代, and some input/output. Each project above is exactly that shape — build small pieces, then join them.

    Common mistakes

    • Build in small steps and test each part before moving on — do not write it all at once.
    • Read the whole task first, then plan the input → process → output before you code.
    한국어

    미니 프로젝트는 이전 아이디어들을 결합합니다: 리스트 안의 데이터, 루프 내 선택 문이 있는 함수, 그리고 출력된 결과물입니다. 이는 AP Create Performance Task의 형태이기도 합니다.

    프로젝트: 평균 점수

    def average(marks):
        if len(marks) == 0:
            return 0
        return round(sum(marks) / len(marks), 1)
    
    print(average([88, 71, 95, 60]))   # 78.5
    

    프로젝트: 합격자 수 세기

    def count_passes(marks, pass_mark=60):
        passes = 0
        for m in marks:                 # iteration
            if m >= pass_mark:          # selection
                passes += 1
        return passes
    
    print(count_passes([88, 50, 95, 60]))   # 3
    

    프로젝트: 새 리스트로 필터링하기

    def merit(marks):
        return [m for m in marks if m >= 80]
    
    print(merit([88, 71, 95, 60]))     # [88, 95]
    

    AP Create Task는 리스트, 선택 및 반복을 사용하는 매개변수가 있는 프로시저, 그리고 일부 입력/출력을 요구합니다. 위의 각 프로젝트는 정확히 그 형태를 띱니다 — 작은 조각을 만들고, 이를 연결하십시오.

    Common mistakes

    • 작은 단계로 만들거나, 다음 단계로 넘어가기 전에 각 부분을 테스트하십시오 — 한 번에 모두 작성하지 마십시오.
    • 먼저 전체 과제를 읽고, 코딩하기 전에 입력 → 처리 → 출력을 계획하십시오.
    미니 프로젝트: 데이터 → 함수 → 출력된 결과
    미니 프로젝트: 데이터 → 함수 → 출력된 결과

Log in or create account · ⁨로그인 또는 계정 만들기⁩

IGCSE, A-Level & AP