파이썬 복습용 코드

JKH·2025년 1월 1일
0

✨ChatGPT Prompt:

  • 파이썬을 복습하기 위해 파이썬의 핵심 개념들을 모두 포함한 코드를 작성해줘.
  • 각 코드별로 어떤 개념이 사용되었는지 주석을 한글로 달아줘.
  • 전체 코드는 500줄 이하로 작성해줘.
# 파이썬 복습용 핵심 개념 코드

# ==========================
# 1. 변수와 데이터 타입
# ==========================
x = 10  # 정수형 변수
name = "Alice"  # 문자열 변수
pi = 3.14  # 실수형 변수
is_happy = True  # 불리언 변수

# ==========================
# 2. 리스트와 튜플
# ==========================
my_list = [1, 2, 3, 4, 5]  # 리스트 생성
my_tuple = (10, 20, 30)  # 튜플 생성

# 리스트 값 추가 및 제거
my_list.append(6)  # 값 추가
my_list.remove(3)  # 값 제거

# 튜플은 불변(immutable)하므로 수정 불가

# ==========================
# 3. 딕셔너리와 집합
# ==========================
my_dict = {"name": "Bob", "age": 25}  # 딕셔너리 생성
my_set = {1, 2, 3, 4}  # 집합 생성

# 딕셔너리 값 추가 및 변경
my_dict["city"] = "Seoul"  # 값 추가
my_dict["age"] = 26  # 값 변경

# 집합 연산
my_set.add(5)  # 값 추가
my_set.discard(3)  # 값 제거

# ==========================
# 4. 조건문
# ==========================
if x > 5:
    print("x는 5보다 큽니다.")
elif x == 5:
    print("x는 5입니다.")
else:
    print("x는 5보다 작습니다.")

# ==========================
# 5. 반복문
# ==========================
# for 반복문
for num in my_list:
    print(num)

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

# ==========================
# 6. 함수
# ==========================
def greet(name):
    """이름을 받아서 환영 메시지를 출력"""
    return f"Hello, {name}!"

message = greet("Charlie")
print(message)

# ==========================
# 7. 클래스
# ==========================
class Person:
    def __init__(self, name, age):
        """생성자 함수"""
        self.name = name
        self.age = age

    def introduce(self):
        """자기소개 메서드"""
        return f"제 이름은 {self.name}이고, 나이는 {self.age}살입니다."

person1 = Person("David", 30)
print(person1.introduce())

# ==========================
# 8. 파일 입출력
# ==========================
with open("example.txt", "w") as file:
    file.write("Hello, Python!\n")

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

# ==========================
# 9. 예외 처리
# ==========================
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print("0으로 나눌 수 없습니다.", e)
finally:
    print("예외 처리 완료.")

# ==========================
# 10. 모듈과 패키지
# ==========================
import math  # 내장 모듈 가져오기

print(math.sqrt(16))  # 제곱근 계산

# ==========================
# 11. 람다 함수와 내장 함수
# ==========================
square = lambda x: x**2  # 람다 함수
print(square(4))

nums = [1, 2, 3, 4]

# map 함수 사용
squared_nums = list(map(lambda x: x**2, nums))
print(squared_nums)

# filter 함수 사용
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums)

# ==========================
# 12. 리스트 컴프리헨션
# ==========================
squares = [x**2 for x in range(1, 6)]  # 리스트 컴프리헨션 사용
print(squares)

# ==========================
# 13. 데코레이터
# ==========================
def my_decorator(func):
    def wrapper():
        print("함수 실행 전 작업")
        func()
        print("함수 실행 후 작업")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

# ==========================
# 14. 제너레이터
# ==========================
def my_generator():
    yield 1
    yield 2
    yield 3

for value in my_generator():
    print(value)

# ==========================
# 15. itertools 사용
# ==========================
import itertools

# 순열 생성
perms = itertools.permutations([1, 2, 3])
print(list(perms))

# 조합 생성
combs = itertools.combinations([1, 2, 3], 2)
print(list(combs))

# ==========================
# 16. NumPy 사용 예제 (외부 라이브러리)
# ==========================
import numpy as np

array = np.array([[1, 2], [3, 4]])
print(array.sum())  # 배열 합계

# ==========================
# 17. 데이터 클래스
# ==========================
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

point = Point(1, 2)
print(point)

# ==========================
# 18. 타이핑
# ==========================
from typing import List, Tuple

def add_numbers(numbers: List[int]) -> int:
    return sum(numbers)

print(add_numbers([1, 2, 3, 4]))

# ==========================
# 19. 비동기 프로그래밍
# ==========================
import asyncio

async def say_after(delay, message):
    await asyncio.sleep(delay)
    print(message)

async def main():
    await asyncio.gather(
        say_after(1, "Hello"),
        say_after(2, "World")
    )

asyncio.run(main())
profile
Connecting my favorite things

0개의 댓글