파이썬 코드 예제

엄선된 파이썬 코드 예제 모음을 통해 새로운 것을 발견하고, 배우고, 영감을 받아보세요. 간단한 스크립트부터 복잡한 애플리케이션까지 다양하게 준비되어 있습니다.

추천 예제

조건문 (미세먼지 농도에 따른 마스크 착용 권고)

# ----------------------------------------------------
# 조건문 (미세먼지 농도에 따른 마스크 착용 권고)
# ----------------------------------------------------

dust_level = int(input("미세먼지 농도를 입력하세요 (단위: ㎍/㎥): "))
if dust_level >= 76:
    print("매우 나쁨: 외출을 자제하고 마스크를 꼭 착용하세요.")
elif dust_level >= 36:
    print("나쁨: 마스크 착용을 권고합니다.")
elif dust_level >= 16:
    print("보통: 마스크를 착용할 필요는 없습니다.")
else:
    print("좋음: 쾌적한 공기입니다!")

반복문 (구구단 출력)

# ----------------------------------------------------
# 반복문 (구구단 출력)
# ---------------------------------------------------- 

dan = int(input("출력하고 싶은 구구단 수를 입력하세요: "))

print(f"--- {dan}단 ---")
for i in range(1, 10):
    print(f"{dan} x {i} = {dan * i}")

리스트 (친구 이름 관리 및 검색)

# ----------------------------------------------------
# 리스트 (친구 이름 관리 및 검색)
# ---------------------------------------------------- 

friends = ["철수", "영희", "민수", "수진"]

print("내 친구들:", friends)

# 친구 추가
new_friend = input("새로운 친구 이름을 입력하세요: ")
friends.append(new_friend)
print("친구 추가 후:", friends)

# 친구 검색
search_name = input("찾고 싶은 친구 이름을 입력하세요: ")
if search_name in friends:
    print(f"{search_name}은(는) 친구 목록에 있습니다.")
else:
    print(f"{search_name}은(는) 친구 목록에 없습니다.")

# 친구 삭제 (예시)
# friends.remove("철수")
# print("철수 삭제 후:", friends)

함수 (간단한 계산기)

# ----------------------------------------------------
# 함수 (간단한 계산기)
# ---------------------------------------------------- 

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "0으로 나눌 수 없습니다."
    else:
        return a / b

num1 = int(input("첫 번째 숫자를 입력하세요: "))
num2 = int(input("두 번째 숫자를 입력하세요: "))
operator = input("연산자를 입력하세요 (+, -, *, /): ")

if operator == '+':
    result = add(num1, num2)
elif operator == '-':
    result = subtract(num1, num2)
elif operator == '*':
    result = multiply(num1, num2)
elif operator == '/':
    result = divide(num1, num2)
else:
    result = "잘못된 연산자입니다."

print(f"결과: {result}")

CSV 파일 읽고 데이터 처리 (간단한 성적 처리)

# ----------------------------------------------------
# CSV 파일 읽고 데이터 처리 (간단한 성적 처리)
# ---------------------------------------------------- 

import csv

# 가상의 성적 데이터 (students.csv 파일로 저장한다고 가정)
# 이름,국어,영어,수학
# 김철수,90,85,92
# 이영희,78,92,88
# 박민수,95,70,80

# 'students.csv' 파일 생성 (실제 실행 시 이 부분을 주석 해제하거나 파일을 직접 생성해야 합니다.)
# with open('students.csv', 'w', newline='', encoding='utf-8') as f:
#     writer = csv.writer(f)
#     writer.writerow(['이름', '국어', '영어', '수학'])
#     writer.writerow(['김철수', 90, 85, 92])
#     writer.writerow(['이영희', 78, 92, 88])
#     writer.writerow(['박민수', 95, 70, 80])


try:
    with open('students.csv', 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        header = next(reader)  # 헤더 읽기
        
        print("--- 학생 성적 평균 ---")
        for row in reader:
            name = row[0]
            korean = int(row[1])
            english = int(row[2])
            math = int(row[3])
            
            average = (korean + english + math) / 3
            print(f"{name}의 평균 점수: {average:.2f}점") # 소수점 둘째자리까지 표시

except FileNotFoundError:
    print("students.csv 파일을 찾을 수 없습니다. 파일을 생성해주세요.")
except Exception as e:
    print(f"오류 발생: {e}")

간단한 규칙 기반 챗봇 (인공지능의 한 예시)

# ----------------------------------------------------
# 간단한 규칙 기반 챗봇 (인공지능의 한 예시)
# ---------------------------------------------------- 

def simple_chatbot(message):
    message = message.lower() # 소문자로 변환하여 비교

    if "안녕" in message or "hi" in message:
        return "안녕하세요! 무엇을 도와드릴까요?"
    elif "날씨" in message:
        return "오늘 날씨는 맑고 쾌청합니다!" # 실제 날씨 API 연결은 어려움
    elif "이름" in message:
        return "저는 AI 챗봇입니다."
    elif "고마워" in message or "땡큐" in message:
        return "천만에요! 또 궁금한 거 있으세요?"
    elif "종료" in message or "exit" in message:
        return "다음에 또 만나요!"
    else:
        return "죄송해요, 이해하지 못했습니다. 다른 질문을 해주세요."

print("간단한 챗봇과 대화해보세요. '종료'를 입력하면 대화가 끝납니다.")
while True:
    user_input = input("나: ")
    if user_input.lower() == "종료":
        print(simple_chatbot(user_input))
        break
    
    response = simple_chatbot(user_input)
    print(f"챗봇: {response}")

기본 도형 그리기: 사각형과 삼각형

# ----------------------------------------------------
# 기본 도형 그리기: 사각형과 삼각형
# ---------------------------------------------------- 

import turtle # turtle 모듈을 불러옵니다.

# 펜 설정 (선택 사항)
turtle.speed(1)  # 거북이 속도 설정 (1: 가장 느림, 10: 빠름, 0: 즉시)
turtle.pensize(3) # 펜 두께 설정
turtle.color("blue") # 펜 색상 설정

# 사각형 그리기
print("사각형을 그립니다.")
for _ in range(4): # 4번 반복
    turtle.forward(100) # 100만큼 앞으로 이동
    turtle.right(90) # 오른쪽으로 90도 회전

# 위치 이동 (펜을 들고 이동해야 선이 안 그려집니다)
turtle.penup() # 펜을 듭니다.
turtle.goto(-150, 50) # 특정 좌표로 이동합니다.
turtle.pendown() # 펜을 내립니다.

# 삼각형 그리기
turtle.color("red") # 펜 색상 변경
print("삼각형을 그립니다.")
for _ in range(3): # 3번 반복
    turtle.forward(100)
    turtle.right(120) # 정삼각형을 위해 120도 회전

turtle.done() # 그림이 그려진 창을 유지합니다.

별 그리기

# ----------------------------------------------------
# 별 그리기
# ---------------------------------------------------- 

import turtle

screen = turtle.Screen() # 화면 객체 생성
screen.bgcolor("black") # 배경색을 검정색으로 설정

star = turtle.Turtle() # 거북이 객체 생성
star.color("gold") # 별 색상 설정
star.pensize(2)
star.speed(5)

print("별을 그립니다.")
for i in range(5): # 오각별
    star.forward(150)
    star.right(144) # 360 / 5 = 72, 72 * 2 = 144 (오각별 각도 계산)

star.penup()
star.goto(100, -100)
star.pendown()
star.color("lightblue")
star.speed(8)

print("작은 별들을 그립니다.")
for _ in range(20): # 작은 별 여러 개 그리기
    for i in range(5):
        star.forward(30)
        star.right(144)
    star.penup()
    star.forward(20) # 조금씩 이동하며 그리기
    star.right(18) # 별들 간의 간격
    star.pendown()

turtle.done()

원 그리기와 색 채우기

# ----------------------------------------------------
# 원 그리기와 색 채우기
# ---------------------------------------------------- 

import turtle

circle_turtle = turtle.Turtle()
circle_turtle.speed(5)
circle_turtle.pensize(2)

print("색이 채워진 원을 그립니다.")
circle_turtle.color("purple", "lightgreen") # 펜 색상, 채울 색상
circle_turtle.begin_fill() # 색 채우기 시작
circle_turtle.circle(80) # 반지름이 80인 원을 그립니다.
circle_turtle.end_fill() # 색 채우기 종료

# 여러 개의 원 그리기 (위치 이동)
circle_turtle.penup()
circle_turtle.goto(-100, 100)
circle_turtle.pendown()

print("여러 개의 원을 그립니다.")
circle_turtle.color("orange", "yellow")
circle_turtle.begin_fill()
circle_turtle.circle(50)
circle_turtle.end_fill()

circle_turtle.penup()
circle_turtle.goto(100, 100)
circle_turtle.pendown()

circle_turtle.color("cyan", "blue")
circle_turtle.begin_fill()
circle_turtle.circle(60)
circle_turtle.end_fill()

turtle.done()

함수를 이용한 복잡한 패턴 그리기 (나선형)

# ----------------------------------------------------
# 함수를 이용한 복잡한 패턴 그리기 (나선형)
# ---------------------------------------------------- 

import turtle

spiral_turtle = turtle.Turtle()
spiral_turtle.speed(0) # 가장 빠른 속도

print("나선형 패턴을 그립니다.")
colors = ["red", "purple", "blue", "green", "orange", "yellow"]
for i in range(300):
    spiral_turtle.pencolor(colors[i % 6]) # 펜 색상 변경 (6가지 색상 반복)
    spiral_turtle.forward(i) # 이동 거리를 점차 늘림
    spiral_turtle.left(59) # 회전 각도 (나선형 모양을 만듦)

turtle.done()

클릭 이벤트 활용 (화면 클릭 시 점 찍기)

#----------------------------------------------------
# 클릭 이벤트 활용 (화면 클릭 시 점 찍기)
#---------------------------------------------------- 

import turtle

screen = turtle.Screen()
screen.setup(width=600, height=400) # 화면 크기 설정
screen.title("클릭하면 점 찍기")

dot_painter = turtle.Turtle()
dot_painter.shape("turtle") # 거북이 모양을 거북이 아이콘으로 변경
dot_painter.color("green")
dot_painter.penup() # 처음에는 펜을 들고 시작

def draw_dot(x, y):
    dot_painter.goto(x, y) # 클릭한 위치로 이동
    dot_painter.dot(10, "red") # 반지름 10인 빨간색 점을 찍습니다.
    print(f"클릭한 위치: ({x}, {y})")

print("화면을 클릭하면 점이 찍힙니다. 닫으려면 창을 닫으세요.")
screen.onclick(draw_dot) # 화면 클릭 이벤트를 draw_dot 함수에 연결

turtle.done()

단순 나선형 원 (반지름이 점점 커지는 형태)

# ----------------------------------------------------
# 단순 나선형 원 (반지름이 점점 커지는 형태)
# ---------------------------------------------------- 

import turtle

# 화면 설정
screen = turtle.Screen()
screen.setup(width=700, height=700) # 화면 크기 설정
screen.bgcolor("black")            # 배경색을 검정으로

# 거북이 객체 생성
spiral_pen = turtle.Turtle()
spiral_pen.speed(0)  # 가장 빠른 속도로 설정 (0이 가장 빠름)
spiral_pen.pencolor("lime") # 펜 색상 설정

print("나선형 원을 그립니다 (반지름 증가).")

# 나선형 원 그리기
# 시작 반지름
radius = 10
# 증가량
radius_increase = 2

for i in range(100): # 100번 반복
    spiral_pen.circle(radius) # 현재 반지름으로 원 그리기
    radius += radius_increase # 반지름을 증가

    # 원을 다 그릴 때마다 조금씩 회전하여 나선형 효과를 강조
    # 이 부분을 조절하여 나선형의 밀도를 바꿀 수 있습니다.
    spiral_pen.right(5) # 오른쪽으로 5도 회전

turtle.done() # 그림이 완료되면 창을 유지합니다.

좀 더 복잡하고 시각적으로 흥미로운 나선형 (다채로운 색상)

# ----------------------------------------------------
# 좀 더 복잡하고 시각적으로 흥미로운 나선형 (다채로운 색상)
# ---------------------------------------------------- 

import turtle
import colorsys # 색상 시스템 모듈

# 화면 설정
screen = turtle.Screen()
screen.setup(width=700, height=700)
screen.bgcolor("black")

# 거북이 객체 생성
fancy_spiral_pen = turtle.Turtle()
fancy_spiral_pen.speed(0)
fancy_spiral_pen.pensize(2) # 펜 두께 설정

print("다채로운 나선형 패턴을 그립니다.")

# 나선형 패턴 그리기
# 'i'가 증가할수록 이동 거리와 색상이 변합니다.
for i in range(360): # 360번 반복 (각도와 연관 지어 생각하기 좋음)
    # HSV 색상 모델을 RGB로 변환하여 다양한 색상 생성
    # hue (색상) 값을 0에서 1까지 변화시키면 무지개색 순환
    c = colorsys.hsv_to_rgb(i / 360, 1, 1) # i / 360은 0.0 ~ 0.99... 범위
    fancy_spiral_pen.pencolor(c) # 펜 색상 설정

    fancy_spiral_pen.forward(i) # 앞으로 이동 거리를 점차 늘림
    fancy_spiral_pen.left(59)  # 왼쪽으로 59도 회전 (나선형 모양을 만듦)

turtle.done()

과일 판매량

import matplotlib.pyplot as plt

# 데이터 준비
categories = ['사과', '바나나', '오렌지', '딸기']
values = [25, 30, 15, 20]

# 막대 그래프 그리기
plt.bar(categories, values, color=['red', 'yellow', 'orange', 'pink']) # 막대 색상 지정

# 제목 및 축 라벨 설정
plt.title("과일 판매량")
plt.xlabel("과일 종류")
plt.ylabel("판매량 (개)")


plt.show()

[matplotlib] Infinite lines

import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(-10, 10, 100)
sig = 1 / (1 + np.exp(-t))

fig, ax = plt.subplots()
ax.axhline(y=0, color="black", linestyle="--")
ax.axhline(y=0.5, color="black", linestyle=":")
ax.axhline(y=1.0, color="black", linestyle="--")
ax.axvline(color="grey")
ax.axline((0, 0.5), slope=0.25, color="black", linestyle=(0, (5, 5)))
ax.plot(t, sig, linewidth=2, label=r"$\sigma(t) = \frac{1}{1 + e^{-t}}$")
ax.set(xlim=(-10, 10), xlabel="t")
ax.legend(fontsize=14)
plt.show()

[matplotlib] Bar chart with individual bar colors

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']

ax.bar(fruits, counts, label=bar_labels, color=bar_colors)

ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')

plt.show()

[matplotlib] Plotting the coherence of two signals

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)

dt = 0.01
t = np.arange(0, 30, dt)
nse1 = np.random.randn(len(t))                 # white noise 1
nse2 = np.random.randn(len(t))                 # white noise 2

# Two signals with a coherent part at 10 Hz and a random part
s1 = np.sin(2 * np.pi * 10 * t) + nse1
s2 = np.sin(2 * np.pi * 10 * t) + nse2

fig, axs = plt.subplots(2, 1, layout='constrained')
axs[0].plot(t, s1, t, s2)
axs[0].set_xlim(0, 2)
axs[0].set_xlabel('Time (s)')
axs[0].set_ylabel('s1 and s2')
axs[0].grid(True)

cxy, f = axs[1].cohere(s1, s2, NFFT=256, Fs=1. / dt)
axs[1].set_ylabel('Coherence')

plt.show()

[matplotlib] Scatter plot with masked values

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


N = 100
r0 = 0.6
x = 0.9 * np.random.rand(N)
y = 0.9 * np.random.rand(N)
area = (20 * np.random.rand(N))**2  # 0 to 10 point radii
c = np.sqrt(area)
r = np.sqrt(x ** 2 + y ** 2)
area1 = np.ma.masked_where(r < r0, area)
area2 = np.ma.masked_where(r >= r0, area)
plt.scatter(x, y, s=area1, marker='^', c=c)
plt.scatter(x, y, s=area2, marker='o', c=c)
# Show the boundary between the regions:
theta = np.arange(0, np.pi / 2, 0.01)
plt.plot(r0 * np.cos(theta), r0 * np.sin(theta))

plt.show()

Python Turtle Parking Simulation

import turtle

# 화면 설정
screen = turtle.Screen()
screen.title("Python Turtle Parking Simulation")
screen.bgcolor("lightgray")
screen.setup(width=800, height=600)

# 주차 슬롯 그리기
def draw_parking_slot(x, y, width=80, height=150):
    slot = turtle.Turtle()
    slot.penup()
    slot.goto(x, y)
    slot.pendown()
    slot.color("black")
    slot.pensize(3)
    for _ in range(2):
        slot.forward(width)
        slot.left(90)
        slot.forward(height)
        slot.left(90)
    slot.hideturtle()

# 주차장 만들기 (5개 슬롯)
start_x = -300
for i in range(5):
    draw_parking_slot(start_x + i * 120, 100)

# 차량 생성
car = turtle.Turtle()
car.shape("square")
car.shapesize(stretch_wid=3, stretch_len=2)
car.color("blue")
car.penup()
car.goto(0, -200)

# 차량 이동 함수
def move_forward():
    car.sety(car.ycor() + 20)

def move_backward():
    car.sety(car.ycor() - 20)

def move_left():
    car.setx(car.xcor() - 20)

def move_right():
    car.setx(car.xcor() + 20)

# 키 바인딩
screen.listen()
screen.onkeypress(move_forward, "Up")
screen.onkeypress(move_backward, "Down")
screen.onkeypress(move_left, "Left")
screen.onkeypress(move_right, "Right")

screen.mainloop()