NyangPolice's homepage

Bookmark this to keep an eye on my project updates!

View on GitHub
20 January 2024

Python 기초: 제어문 (조건문과 반복문)

by NyangPolice

Python 기초: 제어문 (조건문과 반복문)

Python의 제어문을 통해 프로그램의 흐름을 제어할 수 있습니다.

조건문 (if, elif, else)

기본 if 문

age = 20

if age >= 18:
    print("성인입니다")
else:
    print("미성년자입니다")

elif 사용

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"학점: {grade}")

중첩 조건문

age = 25
has_license = True

if age >= 18:
    if has_license:
        print("운전 가능합니다")
    else:
        print("면허가 필요합니다")
else:
    print("미성년자는 운전할 수 없습니다")

반복문

for 문

# 리스트 순회
fruits = ["사과", "바나나", "오렌지"]
for fruit in fruits:
    print(fruit)

# range() 함수 사용
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# 딕셔너리 순회
person = {"name": "홍길동", "age": 25, "city": "서울"}
for key, value in person.items():
    print(f"{key}: {value}")

while 문

# 기본 while 문
count = 0
while count < 5:
    print(count)
    count += 1

# break와 continue
num = 0
while True:
    num += 1
    if num == 3:
        continue  # 다음 반복으로
    if num > 5:
        break     # 반복문 종료
    print(num)

리스트 컴프리헨션

# 기존 방식
squares = []
for x in range(10):
    squares.append(x**2)

# 리스트 컴프리헨션
squares = [x**2 for x in range(10)]

# 조건문 포함
even_squares = [x**2 for x in range(10) if x % 2 == 0]

실전 예제

# 점수 리스트에서 합격자 찾기
scores = [85, 92, 78, 96, 65, 88]
passed = [score for score in scores if score >= 80]
print(f"합격자 점수: {passed}")

# 구구단 출력
for i in range(2, 10):
    for j in range(1, 10):
        print(f"{i} x {j} = {i*j}")
    print()

제어문을 잘 활용하면 복잡한 로직도 쉽게 구현할 수 있습니다!

tags: python - 기초 - 제어문 - 조건문 - 반복문

Python 카테고리의 글 목록

Python 카테고리 페이지로 이동 →