1. 기본 문법
# 변수 선언 및 출력
a = 10
b = 20
print(a + b) # 30
# 들여쓰기 (Indentation)
if a > 5:
print("a는 5보다 크다") # 들여쓰기 필수!
2. 데이터 타입
# 숫자형
x = 10 # 정수 (int)
y = 10.5 # 실수 (float)
z = 1 + 2j # 복소수 (complex)
# 문자열
s1 = "Hello"
s2 = 'Python'
s3 = """여러 줄 문자열"""
# 리스트 (mutable)
lst = [1, 2, 3, "hello"]
# 튜플 (immutable)
tpl = (1, 2, 3, "hello")
# 세트 (중복 불가)
st = {1, 2, 3, 3, 4}
# 딕셔너리 (key-value)
dct = {"name": "John", "age": 25}
3. 연산자
# 산술 연산자
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333
print(a // b) # 3 (몫)
print(a % b) # 1 (나머지)
print(a ** b) # 1000 (거듭제곱)
# 비교 연산자
print(a > b) # True
print(a < b) # False
print(a == b) # False
print(a != b) # True
# 논리 연산자
x, y = True, False
print(x and y) # False
print(x or y) # True
print(not x) # False
# 멤버십 연산자
print(2 in lst) # True
print("name" in dct) # True
4. 조건문
a = 10
if a > 10:
print("10보다 크다")
elif a == 10:
print("10이다")
else:
print("10보다 작다")
5. 반복문
# for 문
for i in range(5): # 0부터 4까지 반복
print(i)
# while 문
i = 0
while i < 5:
print(i)
i += 1
# 리스트 순회
for item in [1, 2, 3, 4]:
print(item)
# 딕셔너리 순회
for key, value in dct.items():
print(key, value)
6. 함수
# 기본 함수
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
# 기본값 매개변수
def add(a, b=10):
return a + b
print(add(5)) # 15
print(add(5, 20)) # 25
# 가변 인자 (*args)
def total(*args):
return sum(args)
print(total(1, 2, 3, 4)) # 10
8. 파일 입출력
# 파일 쓰기
with open("test.txt", "w") as f:
f.write("Hello, Python!")
# 파일 읽기
with open("test.txt", "r") as f:
content = f.read()
print(content)
10. 람다 함수
square = lambda x: x ** 2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 7)) # 10
11. 리스트 컴프리헨션
nums = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in nums]
print(squared) # [1, 4, 9, 16, 25]
even_numbers = [x for x in nums if x % 2 == 0]
print(even_numbers) # [2, 4]
13. 날짜와 시간
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2025-02-25 15:30:45 (예시)
15. 웹 크롤링 (Requests & BeautifulSoup)
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.text)