This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
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(...)로 감싸야 합니다.
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)
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:
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)는 키가 없을 때 기본값을 반환하며, 오류를 발생시키지 않습니다.
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
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하여 충돌하지 않고 처리합니다.
특정 타입의 예외를 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, 매우 큰 값 — 모두 시도하십시오.
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:을 사용하여 자동으로 닫게 하십시오.
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)의 콜 스택: 각 호출이 대기했다가 역순으로 반환
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
재귀에는 기본 케이스가 필요하며, 그렇지 않으면 무한히 자신을 호출하여 호출 스택이 충돌합니다.
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.
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으로 끝납니다
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은 해시 테이블이므로 검색이 빠릅니다.
해시 함수는 각 키를 슬롯에 매핑합니다. 두 개의 키가 하나의 슬롯에서 충돌할 수 있습니다
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)
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) 방식보다 빠른 것은 매우 작은 입력일 때に限정됩니다.
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
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__은 새 객체를 설정하고, 객체를 생성할 때 자동으로 실행됩니다.
같은 클래스의 두 객체는 독립적인 속성을 가집니다.其中一个의 변경은 다른 쪽에 영향을 주지 않습니다.
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.
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.
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
인터넷과 월드 와이드 웹은 다릅니다: 웹은 인터넷 위에서 작동하는 하나의 서비스입니다.
더 많은 프로세서 코어가 도움이 되려면 작업이 동시에 실행되는 부분으로 나뉠 수 있어야 합니다.
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의 형태이기도 합니다.