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)