Python Basics

Python Basics

Note: This lesson is for reviewing prerequisite knowledge. If you lack foundational knowledge before starting advanced lessons, study this content first.

Learning Objectives

  • Understand Python basic data types and operators
  • Utilize control flow statements (conditionals, loops)
  • Master function definition and calling
  • Utilize data structures (lists, dictionaries, tuples, sets)

1. Variables and Data Types

1.1 Basic Data Types

# ์ •์ˆ˜ (int)
age = 25
count = -10
big_number = 1_000_000  # ๊ฐ€๋…์„ฑ์„ ์œ„ํ•œ ์–ธ๋”์Šค์ฝ”์–ด

# ์‹ค์ˆ˜ (float)
pi = 3.14159
temperature = -40.5
scientific = 2.5e-3  # 0.0025

# ๋ฌธ์ž์—ด (str)
name = "Alice"
message = '์•ˆ๋…•ํ•˜์„ธ์š”'
multiline = """์—ฌ๋Ÿฌ ์ค„
๋ฌธ์ž์—ด์ž…๋‹ˆ๋‹ค"""

# ๋ถˆ๋ฆฌ์–ธ (bool)
is_active = True
is_empty = False

# None (๊ฐ’ ์—†์Œ)
result = None

# ํƒ€์ž… ํ™•์ธ
print(type(age))        # <class 'int'>
print(type(pi))         # <class 'float'>
print(type(name))       # <class 'str'>
print(type(is_active))  # <class 'bool'>

1.2 Type Conversion

# ๋ฌธ์ž์—ด โ†’ ์ •์ˆ˜/์‹ค์ˆ˜
num_str = "123"
num_int = int(num_str)      # 123
num_float = float(num_str)  # 123.0

# ์ˆซ์ž โ†’ ๋ฌธ์ž์—ด
age = 25
age_str = str(age)  # "25"

# ๋ถˆ๋ฆฌ์–ธ ๋ณ€ํ™˜
bool(0)       # False
bool(1)       # True
bool("")      # False (๋นˆ ๋ฌธ์ž์—ด)
bool("hello") # True
bool([])      # False (๋นˆ ๋ฆฌ์ŠคํŠธ)
bool([1, 2])  # True

# ํ˜•๋ณ€ํ™˜ ์˜ค๋ฅ˜ ์ฒ˜๋ฆฌ
try:
    invalid = int("hello")
except ValueError as e:
    print(f"๋ณ€ํ™˜ ์˜ค๋ฅ˜: {e}")

1.3 Operators

# ์‚ฐ์ˆ  ์—ฐ์‚ฐ์ž
a, b = 10, 3
print(a + b)   # 13 (๋ง์…ˆ)
print(a - b)   # 7 (๋บ„์…ˆ)
print(a * b)   # 30 (๊ณฑ์…ˆ)
print(a / b)   # 3.333... (๋‚˜๋ˆ—์…ˆ, ํ•ญ์ƒ float)
print(a // b)  # 3 (์ •์ˆ˜ ๋‚˜๋ˆ—์…ˆ)
print(a % b)   # 1 (๋‚˜๋จธ์ง€)
print(a ** b)  # 1000 (๊ฑฐ๋“ญ์ œ๊ณฑ)

# ๋น„๊ต ์—ฐ์‚ฐ์ž
print(5 == 5)   # True
print(5 != 3)   # True
print(5 > 3)    # True
print(5 >= 5)   # True
print(3 < 5)    # True
print(3 <= 3)   # True

# ๋…ผ๋ฆฌ ์—ฐ์‚ฐ์ž
print(True and False)  # False
print(True or False)   # True
print(not True)        # False

# ๋ฉค๋ฒ„์‹ญ ์—ฐ์‚ฐ์ž
fruits = ["apple", "banana"]
print("apple" in fruits)      # True
print("orange" not in fruits) # True

# ๋™์ผ์„ฑ ์—ฐ์‚ฐ์ž (๊ฐ์ฒด ๋น„๊ต)
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b)  # True (๊ฐ’ ๋น„๊ต)
print(a is b)  # False (๊ฐ์ฒด ๋น„๊ต)
print(a is c)  # True (๊ฐ™์€ ๊ฐ์ฒด)

2. String Processing

2.1 String Basics

# ๋ฌธ์ž์—ด ์ƒ์„ฑ
s1 = "Hello"
s2 = 'World'
s3 = """Multi
line"""

# ๋ฌธ์ž์—ด ์—ฐ๊ฒฐ
greeting = s1 + " " + s2  # "Hello World"

# ๋ฌธ์ž์—ด ๋ฐ˜๋ณต
dashes = "-" * 10  # "----------"

# ์ธ๋ฑ์‹ฑ (0๋ถ€ํ„ฐ ์‹œ์ž‘)
text = "Python"
print(text[0])   # 'P'
print(text[-1])  # 'n' (๋งˆ์ง€๋ง‰)

# ์Šฌ๋ผ์ด์‹ฑ
print(text[0:3])   # 'Pyt' (0~2)
print(text[2:])    # 'thon' (2๋ถ€ํ„ฐ ๋)
print(text[:3])    # 'Pyt' (์ฒ˜์Œ~2)
print(text[::2])   # 'Pto' (2์นธ์”ฉ)
print(text[::-1])  # 'nohtyP' (์—ญ์ˆœ)

2.2 String Methods

text = "  Hello, World!  "

# ๊ณต๋ฐฑ ์ œ๊ฑฐ
print(text.strip())   # "Hello, World!"
print(text.lstrip())  # "Hello, World!  "
print(text.rstrip())  # "  Hello, World!"

# ๋Œ€์†Œ๋ฌธ์ž ๋ณ€ํ™˜
s = "Hello World"
print(s.upper())       # "HELLO WORLD"
print(s.lower())       # "hello world"
print(s.capitalize())  # "Hello world"
print(s.title())       # "Hello World"

# ๊ฒ€์ƒ‰
print(s.find("World"))     # 6 (์ธ๋ฑ์Šค)
print(s.find("Python"))    # -1 (์—†์Œ)
print(s.count("o"))        # 2
print(s.startswith("He"))  # True
print(s.endswith("!"))     # False

# ๋ถ„๋ฆฌ์™€ ๊ฒฐํ•ฉ
csv = "a,b,c,d"
parts = csv.split(",")     # ['a', 'b', 'c', 'd']
joined = "-".join(parts)   # 'a-b-c-d'

# ์น˜ํ™˜
text = "I like Python"
new_text = text.replace("Python", "Java")  # "I like Java"

2.3 Formatting

name = "Alice"
age = 25
score = 95.5

# f-string (๊ถŒ์žฅ, Python 3.6+)
print(f"Name: {name}, Age: {age}")
print(f"Score: {score:.2f}")  # ์†Œ์ˆ˜์  2์ž๋ฆฌ
print(f"Binary: {age:08b}")   # 8์ž๋ฆฌ ์ด์ง„์ˆ˜, 0ํŒจ๋”ฉ

# format() ๋ฉ”์„œ๋“œ
print("Name: {}, Age: {}".format(name, age))
print("Name: {n}, Age: {a}".format(n=name, a=age))

# % ์—ฐ์‚ฐ์ž (๊ตฌ ๋ฐฉ์‹)
print("Name: %s, Age: %d" % (name, age))

# ์ •๋ ฌ
text = "Python"
print(f"{text:>10}")   # "    Python" (์˜ค๋ฅธ์ชฝ ์ •๋ ฌ)
print(f"{text:<10}")   # "Python    " (์™ผ์ชฝ ์ •๋ ฌ)
print(f"{text:^10}")   # "  Python  " (๊ฐ€์šด๋ฐ ์ •๋ ฌ)
print(f"{text:*^10}")  # "**Python**" (ํŒจ๋”ฉ ๋ฌธ์ž)

3. Control Flow

3.1 Conditionals (if)

# ๊ธฐ๋ณธ if-elif-else
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"Grade: {grade}")  # Grade: B

# ์‚ผํ•ญ ์—ฐ์‚ฐ์ž
status = "Pass" if score >= 60 else "Fail"

# ์กฐ๊ฑด์‹ ์ฒด์ด๋‹
age = 25
if 18 <= age < 65:
    print("Working age")

# ์ง„๋ฆฌ๊ฐ’ ํŒ๋‹จ
items = [1, 2, 3]
if items:  # ๋น„์–ด์žˆ์ง€ ์•Š์œผ๋ฉด True
    print("List has items")

# ๋…ผ๋ฆฌ ์—ฐ์‚ฐ ์กฐํ•ฉ
x, y = 5, 10
if x > 0 and y > 0:
    print("Both positive")

if x < 0 or y < 0:
    print("At least one negative")

3.2 Loops (for)

# ๋ฆฌ์ŠคํŠธ ๋ฐ˜๋ณต
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# range ์‚ฌ์šฉ
for i in range(5):        # 0, 1, 2, 3, 4
    print(i)

for i in range(2, 8):     # 2, 3, 4, 5, 6, 7
    print(i)

for i in range(0, 10, 2): # 0, 2, 4, 6, 8
    print(i)

# enumerate (์ธ๋ฑ์Šค์™€ ๊ฐ’)
for idx, fruit in enumerate(fruits):
    print(f"{idx}: {fruit}")

# zip (์—ฌ๋Ÿฌ ์‹œํ€€์Šค ๋ณ‘๋ ฌ ์ˆœํšŒ)
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age}")

# ๋”•์…”๋„ˆ๋ฆฌ ๋ฐ˜๋ณต
person = {"name": "Alice", "age": 25}
for key in person:
    print(f"{key}: {person[key]}")

for key, value in person.items():
    print(f"{key}: {value}")

# ๋ฆฌ์ŠคํŠธ ์ปดํ”„๋ฆฌํ—จ์…˜
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

3.3 Loops (while)

# ๊ธฐ๋ณธ while
count = 0
while count < 5:
    print(count)
    count += 1

# break์™€ continue
for i in range(10):
    if i == 3:
        continue  # 3 ๊ฑด๋„ˆ๋›ฐ๊ธฐ
    if i == 7:
        break     # 7์—์„œ ์ข…๋ฃŒ
    print(i)  # 0, 1, 2, 4, 5, 6

# while-else (break ์—†์ด ๋๋‚ฌ์„ ๋•Œ)
n = 7
i = 2
while i < n:
    if n % i == 0:
        print(f"{n} is not prime")
        break
    i += 1
else:
    print(f"{n} is prime")

# ๋ฌดํ•œ ๋ฃจํ”„
while True:
    user_input = input("Enter 'quit' to exit: ")
    if user_input == "quit":
        break

4. Functions

4.1 Function Definition

# ๊ธฐ๋ณธ ํ•จ์ˆ˜
def greet(name):
    """์ธ์‚ฌ๋ง์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค."""
    return f"Hello, {name}!"

message = greet("Alice")
print(message)  # Hello, Alice!

# ์—ฌ๋Ÿฌ ๊ฐ’ ๋ฐ˜ํ™˜
def divide(a, b):
    quotient = a // b
    remainder = a % b
    return quotient, remainder

q, r = divide(10, 3)
print(f"๋ชซ: {q}, ๋‚˜๋จธ์ง€: {r}")  # ๋ชซ: 3, ๋‚˜๋จธ์ง€: 1

# ๊ธฐ๋ณธ๊ฐ’ ๋งค๊ฐœ๋ณ€์ˆ˜
def power(base, exp=2):
    return base ** exp

print(power(3))     # 9
print(power(3, 3))  # 27

# ํ‚ค์›Œ๋“œ ์ธ์ž
def create_user(name, age, city="Seoul"):
    return {"name": name, "age": age, "city": city}

user = create_user(name="Bob", age=30, city="Busan")

4.2 Variable Arguments

# *args (์œ„์น˜ ์ธ์ž)
def sum_all(*args):
    """์ž„์˜ ๊ฐœ์ˆ˜์˜ ์ˆซ์ž ํ•ฉ๊ณ„"""
    return sum(args)

print(sum_all(1, 2, 3))       # 6
print(sum_all(1, 2, 3, 4, 5)) # 15

# **kwargs (ํ‚ค์›Œ๋“œ ์ธ์ž)
def print_info(**kwargs):
    """์ž„์˜ ๊ฐœ์ˆ˜์˜ ํ‚ค-๊ฐ’ ์ถœ๋ ฅ"""
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="Seoul")

# ํ˜ผํ•ฉ ์‚ฌ์šฉ
def mixed_func(required, *args, **kwargs):
    print(f"ํ•„์ˆ˜: {required}")
    print(f"์ถ”๊ฐ€ ์œ„์น˜: {args}")
    print(f"์ถ”๊ฐ€ ํ‚ค์›Œ๋“œ: {kwargs}")

mixed_func("hello", 1, 2, 3, x=10, y=20)

4.3 Lambda Functions

# ๊ธฐ๋ณธ ๋žŒ๋‹ค
square = lambda x: x ** 2
print(square(5))  # 25

# ์—ฌ๋Ÿฌ ๋งค๊ฐœ๋ณ€์ˆ˜
add = lambda a, b: a + b
print(add(3, 4))  # 7

# ์ •๋ ฌ์—์„œ ํ™œ์šฉ
students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78}
]

# ์ ์ˆ˜ ๊ธฐ์ค€ ์ •๋ ฌ
sorted_students = sorted(students, key=lambda x: x["score"], reverse=True)
for s in sorted_students:
    print(f"{s['name']}: {s['score']}")

# map, filter์™€ ํ•จ๊ป˜
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
evens = list(filter(lambda x: x % 2 == 0, numbers))

5. Data Structures

5.1 Lists

# ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
empty = []

# ์š”์†Œ ์ ‘๊ทผ
print(fruits[0])   # "apple"
print(fruits[-1])  # "cherry"

# ์Šฌ๋ผ์ด์‹ฑ
print(numbers[1:4])  # [2, 3, 4]
print(numbers[::2])  # [1, 3, 5]

# ์š”์†Œ ์ˆ˜์ •
fruits[0] = "apricot"

# ์š”์†Œ ์ถ”๊ฐ€
fruits.append("date")           # ๋์— ์ถ”๊ฐ€
fruits.insert(1, "blueberry")   # ์œ„์น˜ ์ง€์ • ์ถ”๊ฐ€
fruits.extend(["elderberry"])   # ์—ฌ๋Ÿฌ ๊ฐœ ์ถ”๊ฐ€

# ์š”์†Œ ์ œ๊ฑฐ
fruits.remove("banana")  # ๊ฐ’์œผ๋กœ ์ œ๊ฑฐ
del fruits[0]            # ์ธ๋ฑ์Šค๋กœ ์ œ๊ฑฐ
popped = fruits.pop()    # ๋งˆ์ง€๋ง‰ ์ œ๊ฑฐ ๋ฐ ๋ฐ˜ํ™˜
fruits.clear()           # ์ „์ฒด ์ œ๊ฑฐ

# ๋ฆฌ์ŠคํŠธ ์—ฐ์‚ฐ
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b      # [1, 2, 3, 4, 5, 6]
d = a * 2      # [1, 2, 3, 1, 2, 3]

# ์œ ์šฉํ•œ ๋ฉ”์„œ๋“œ
nums = [3, 1, 4, 1, 5, 9, 2]
print(len(nums))        # 7
print(nums.count(1))    # 2
print(nums.index(4))    # 2
nums.sort()             # ์ •๋ ฌ (์ œ์ž๋ฆฌ)
nums.reverse()          # ์—ญ์ˆœ (์ œ์ž๋ฆฌ)

5.2 Tuples

# ํŠœํ”Œ ์ƒ์„ฑ (๋ถˆ๋ณ€)
point = (3, 4)
rgb = (255, 128, 0)
single = (42,)  # ์š”์†Œ 1๊ฐœ (์‰ผํ‘œ ํ•„์ˆ˜)

# ์–ธํŒจํ‚น
x, y = point
print(f"x={x}, y={y}")

# ํ•จ์ˆ˜์—์„œ ์—ฌ๋Ÿฌ ๊ฐ’ ๋ฐ˜ํ™˜
def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers)

minimum, maximum, total = get_stats([1, 2, 3, 4, 5])

# ํŠœํ”Œ์€ ์ˆ˜์ • ๋ถˆ๊ฐ€
# point[0] = 5  # TypeError!

# ํ•˜์ง€๋งŒ ๊ฐ€๋ณ€ ๊ฐ์ฒด ํฌํ•จ ์‹œ ๋‚ด๋ถ€๋Š” ๋ณ€๊ฒฝ ๊ฐ€๋Šฅ
data = ([1, 2], [3, 4])
data[0].append(3)  # ๊ฐ€๋Šฅ! ([1, 2, 3], [3, 4])

# ํŠœํ”Œ โ†” ๋ฆฌ์ŠคํŠธ ๋ณ€ํ™˜
t = tuple([1, 2, 3])
l = list((1, 2, 3))

5.3 Dictionaries

# ๋”•์…”๋„ˆ๋ฆฌ ์ƒ์„ฑ
person = {
    "name": "Alice",
    "age": 25,
    "city": "Seoul"
}

# ์š”์†Œ ์ ‘๊ทผ
print(person["name"])          # "Alice"
print(person.get("job"))       # None (์—†์„ ๋•Œ)
print(person.get("job", "N/A")) # "N/A" (๊ธฐ๋ณธ๊ฐ’)

# ์š”์†Œ ์ถ”๊ฐ€/์ˆ˜์ •
person["job"] = "Engineer"  # ์ถ”๊ฐ€
person["age"] = 26          # ์ˆ˜์ •

# ์š”์†Œ ์‚ญ์ œ
del person["city"]
job = person.pop("job")
person.clear()

# ๋ฉ”์„œ๋“œ
person = {"name": "Alice", "age": 25}
print(person.keys())    # dict_keys(['name', 'age'])
print(person.values())  # dict_values(['Alice', 25])
print(person.items())   # dict_items([('name', 'Alice'), ('age', 25)])

# ๋”•์…”๋„ˆ๋ฆฌ ์ปดํ”„๋ฆฌํ—จ์…˜
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# ๋ณ‘ํ•ฉ (Python 3.9+)
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
c = a | b  # {"x": 1, "y": 3, "z": 4}

# ์ค‘์ฒฉ ๋”•์…”๋„ˆ๋ฆฌ
users = {
    "user1": {"name": "Alice", "age": 25},
    "user2": {"name": "Bob", "age": 30}
}
print(users["user1"]["name"])  # "Alice"

5.4 Sets

# ์„ธํŠธ ์ƒ์„ฑ (์ค‘๋ณต ์—†์Œ, ์ˆœ์„œ ์—†์Œ)
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 3, 2, 1}  # {1, 2, 3}
empty = set()  # ๋นˆ ์„ธํŠธ ({}๋Š” ๋”•์…”๋„ˆ๋ฆฌ!)

# ์š”์†Œ ์ถ”๊ฐ€/์ œ๊ฑฐ
fruits.add("date")
fruits.remove("apple")    # ์—†์œผ๋ฉด KeyError
fruits.discard("grape")   # ์—†์–ด๋„ ์—๋Ÿฌ ์—†์Œ

# ์ง‘ํ•ฉ ์—ฐ์‚ฐ
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)  # ํ•ฉ์ง‘ํ•ฉ: {1, 2, 3, 4, 5, 6}
print(a & b)  # ๊ต์ง‘ํ•ฉ: {3, 4}
print(a - b)  # ์ฐจ์ง‘ํ•ฉ: {1, 2}
print(a ^ b)  # ๋Œ€์นญ ์ฐจ์ง‘ํ•ฉ: {1, 2, 5, 6}

# ๋ถ€๋ถ„์ง‘ํ•ฉ ํ™•์ธ
c = {1, 2}
print(c.issubset(a))    # True
print(a.issuperset(c))  # True

# ๋ฆฌ์ŠคํŠธ ์ค‘๋ณต ์ œ๊ฑฐ
numbers = [1, 2, 2, 3, 3, 3]
unique = list(set(numbers))  # [1, 2, 3]

6. Exception Handling

6.1 Basic Exception Handling

# try-except
try:
    result = 10 / 0
except ZeroDivisionError:
    print("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค")

# ์—ฌ๋Ÿฌ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ
try:
    value = int(input("์ˆซ์ž ์ž…๋ ฅ: "))
    result = 10 / value
except ValueError:
    print("์ˆซ์ž๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค")
except ZeroDivisionError:
    print("0์œผ๋กœ ๋‚˜๋ˆŒ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค")

# ์˜ˆ์™ธ ์ •๋ณด ์ ‘๊ทผ
try:
    x = int("hello")
except ValueError as e:
    print(f"์—๋Ÿฌ ๋ฐœ์ƒ: {e}")

# else์™€ finally
try:
    file = open("data.txt", "r")
except FileNotFoundError:
    print("ํŒŒ์ผ ์—†์Œ")
else:
    # ์˜ˆ์™ธ ์—†์„ ๋•Œ ์‹คํ–‰
    content = file.read()
    file.close()
finally:
    # ํ•ญ์ƒ ์‹คํ–‰
    print("์ž‘์—… ์™„๋ฃŒ")

6.2 Raising Exceptions

# ์˜ˆ์™ธ ๋ฐœ์ƒ์‹œํ‚ค๊ธฐ
def validate_age(age):
    if age < 0:
        raise ValueError("๋‚˜์ด๋Š” ์Œ์ˆ˜์ผ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค")
    if age > 150:
        raise ValueError("๋‚˜์ด๊ฐ€ ๋„ˆ๋ฌด ํฝ๋‹ˆ๋‹ค")
    return age

try:
    validate_age(-5)
except ValueError as e:
    print(f"๊ฒ€์ฆ ์‹คํŒจ: {e}")

# ์ปค์Šคํ…€ ์˜ˆ์™ธ
class InsufficientFundsError(Exception):
    """์ž”์•ก ๋ถ€์กฑ ์˜ˆ์™ธ"""
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"์ž”์•ก {balance}์›, ์ถœ๊ธˆ ์š”์ฒญ {amount}์›")

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount

try:
    withdraw(1000, 2000)
except InsufficientFundsError as e:
    print(f"์ถœ๊ธˆ ์‹คํŒจ: {e}")

7. File I/O

7.1 File Reading/Writing

# ํŒŒ์ผ ์“ฐ๊ธฐ
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World!\n")
    f.write("์•ˆ๋…•ํ•˜์„ธ์š”\n")

# ํŒŒ์ผ ์ฝ๊ธฐ
with open("output.txt", "r", encoding="utf-8") as f:
    content = f.read()  # ์ „์ฒด ์ฝ๊ธฐ
    print(content)

# ์ค„ ๋‹จ์œ„ ์ฝ๊ธฐ
with open("output.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

# ํŒŒ์ผ ์ถ”๊ฐ€
with open("output.txt", "a", encoding="utf-8") as f:
    f.write("์ถ”๊ฐ€๋œ ๋‚ด์šฉ\n")

# ํŒŒ์ผ ๋ชจ๋“œ
# "r"  ์ฝ๊ธฐ (๊ธฐ๋ณธ)
# "w"  ์“ฐ๊ธฐ (๋ฎ์–ด์“ฐ๊ธฐ)
# "a"  ์ถ”๊ฐ€
# "x"  ์ƒ์„ฑ (์ด๋ฏธ ์žˆ์œผ๋ฉด ์—๋Ÿฌ)
# "b"  ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ชจ๋“œ (์˜ˆ: "rb", "wb")

7.2 JSON Processing

import json

# Python ๊ฐ์ฒด โ†’ JSON
data = {
    "name": "Alice",
    "age": 25,
    "hobbies": ["reading", "coding"]
}

# JSON ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)

# JSON ํŒŒ์ผ๋กœ ์ €์žฅ
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

# JSON ํŒŒ์ผ ์ฝ๊ธฐ
with open("data.json", "r", encoding="utf-8") as f:
    loaded = json.load(f)
    print(loaded["name"])

Summary

Core Syntax Overview

Concept Description Example
Variables Name to store values x = 10
Data Types int, float, str, bool, None type(x)
Lists Ordered mutable sequence [1, 2, 3]
Tuples Ordered immutable sequence (1, 2, 3)
Dictionaries Key-value pairs {"a": 1}
Sets Collection without duplicates {1, 2, 3}
if/elif/else Conditional branching if x > 0:
for Iterate over sequence for i in range(10):
while Conditional loop while x < 10:
Functions Reusable code block def func():
Exception Handling Error handling try/except

Next Steps

After completing these basics, proceed to the next lessons: - 16_OOP_Basics.md: Object-Oriented Programming Basics - 01_Type_Hints.md: Type Hinting (start of advanced lessons)


References

to navigate between lessons