python 기본 문법 정리

Jimin·2025년 1월 21일
0

python

목록 보기
1/1

Python 개요 및 문법 정보

프리평을 위한 Python 기본 문법


1. 변수

Python은 동적 타입을 지원합니다. 변수 선언 시 자료형을 명시하지 않아도 됩니다.

# 숫자 생성
age = 25
height = 180.5

# 문자열
name = "Alice"

# 불리언
is_active = True

2. 함수

Python은 def 키워드를 통해 함수를 정의합니다.

# 기본 함수

def greet(name):
    return f"Hello, {name}!"

print(greet("Python"))  # Hello, Python!

3. 조건문

Python의 조건문은 다양한 조건을 처리할 수 있도록 지원합니다.

age = 18

if age < 20:
    print("미성년자")
elif age < 60:
    print("성인")
else:
    print("노인")

4. 반복문

Python은 for 키워드 및 while 반복을 지원합니다.

# for 반복문
for i in range(5):  # 0~4
    print(i)

# while 반복문
count = 0
while count < 3:
    print(count)
    count += 1

5. 리스트

리스트는 데이터를 순서대로 저장하고 조작할 수 있는 구조입니다.

fruits = ["사과", "바나나", "체리"]

# 접근
print(fruits[0])  # 사과

# 추가
fruits.append("방울토마토")

# 삭제
fruits.remove("바나나")

# 반복
for fruit in fruits:
    print(fruit)

6. 딕셔너리

딕셔너리는 키-값 쌍으로 이루어진 데이터 구조입니다.

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}")

7. 클래스와 객체

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())

8. 상속

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!

9. 클래스 간 DI (Dependency Injection)

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

10. 자주 쓰는 자료구조

리스트

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}

큐 (Queue)

from collections import deque

queue = deque([1, 2, 3])
queue.append(4)
queue.popleft()  # 1 제거

스택 (Stack)

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

11. 파일 입출력

Python에서 파일 입출력은 간단합니다.

# 파일 쓰기
with open("example.txt", "w") as f:
    f.write("Hello, Python!")

# 파일 읽기
with open("example.txt", "r") as f:
    print(f.read())

12. 예외 처리

Python에서 예외 처리는 try-except 블록을 사용합니다.

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("Execution complete")
profile
도전을 좋아하는 개발자

0개의 댓글