Python은 동적 타입을 지원합니다. 변수 선언 시 자료형을 명시하지 않아도 됩니다.
# 숫자 생성
age = 25
height = 180.5
# 문자열
name = "Alice"
# 불리언
is_active = True
Python은 def 키워드를 통해 함수를 정의합니다.
# 기본 함수
def greet(name):
return f"Hello, {name}!"
print(greet("Python")) # Hello, Python!
Python의 조건문은 다양한 조건을 처리할 수 있도록 지원합니다.
age = 18
if age < 20:
print("미성년자")
elif age < 60:
print("성인")
else:
print("노인")
Python은 for 키워드 및 while 반복을 지원합니다.
# for 반복문
for i in range(5): # 0~4
print(i)
# while 반복문
count = 0
while count < 3:
print(count)
count += 1
리스트는 데이터를 순서대로 저장하고 조작할 수 있는 구조입니다.
fruits = ["사과", "바나나", "체리"]
# 접근
print(fruits[0]) # 사과
# 추가
fruits.append("방울토마토")
# 삭제
fruits.remove("바나나")
# 반복
for fruit in fruits:
print(fruit)
딕셔너리는 키-값 쌍으로 이루어진 데이터 구조입니다.
person = {"name": "Alice", "age": 25}
# 접근
print(person["name"]) # Alice
# 추가
person["city"] = "Seoul"
# 삭제
del person["age"]
# 반복
for key, value in person.items():
print(f"{key}: {value}")
Python에서 클래스는 class 키워드를 통해 정의합니다.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"My name is {self.name}, and I'm {self.age} years old."
# 객체 생성
alice = Person("Alice", 25)
print(alice.introduce())
Python에서 상속은 클래스 정의 시 괄호 안에 부모 클래스를 지정합니다.
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.speak()) # Woof!
print(cat.speak()) # Meow!
Python에서 의존성 주입은 생성자를 통해 구현할 수 있습니다.
class Engine:
def start(self):
return "Engine started"
class Car:
def __init__(self, engine: Engine):
self.engine = engine
def drive(self):
return self.engine.start()
# DI 사용
engine = Engine()
car = Car(engine)
print(car.drive()) # Engine started
numbers = [1, 2, 3, 4, 5]
numbers.append(6)
numbers.remove(2)
person = {"name": "John", "age": 30}
unique_numbers = {1, 2, 3, 3, 2}
print(unique_numbers) # {1, 2, 3}
from collections import deque
queue = deque([1, 2, 3])
queue.append(4)
queue.popleft() # 1 제거
stack = []
stack.append(1)
stack.append(2)
stack.pop() # 2 제거
import heapq
heap = []
heapq.heappush(heap, 10)
heapq.heappush(heap, 5)
heapq.heappush(heap, 20)
print(heapq.heappop(heap)) # 5
Python에서 파일 입출력은 간단합니다.
# 파일 쓰기
with open("example.txt", "w") as f:
f.write("Hello, Python!")
# 파일 읽기
with open("example.txt", "r") as f:
print(f.read())
Python에서 예외 처리는 try-except 블록을 사용합니다.
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution complete")