프로그램은 단순히 위에서 아래로 코드를 실행하는 것만으로는 부족하다.
상황에 따라 다른 작업을 실행하거나, 같은 작업을 여러 번 반복해야 한다.
Python에서는 대표적으로 다음 세 가지 제어문을 사용한다.
ifwhileforifstock = 5
if stock > 0:
print("구매 가능")
조건식이 True라면 들여쓰기된 블록이 실행된다.
if ... elsestock = 0
if stock > 0:
print("구매 가능")
else:
print("품절")
조건이 거짓일 때 실행할 코드는 else에 작성한다.
elifscore = 84
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(grade)
위에서부터 조건을 검사하고 처음 참이 된 블록만 실행된다.
age = 30
age == 30
age != 30
age > 20
age >= 30
age < 40
age <= 30
and두 조건이 모두 참이어야 한다.
age = 25
is_member = True
if age >= 19 and is_member:
print("구매 가능")
or둘 중 하나만 참이어도 된다.
role = "manager"
if role == "admin" or role == "manager":
print("관리 메뉴 표시")
not참과 거짓을 뒤집는다.
is_logged_in = False
if not is_logged_in:
print("로그인이 필요합니다.")
in과 not inallowed_roles = [
"admin",
"editor",
]
if "admin" in allowed_roles:
print("권한 있음")
문자열에서도 사용할 수 있다.
url = "/api/users"
if "/api/" in url:
print("API 요청")
간단한 if-else는 한 줄로 표현할 수도 있다.
is_active = True
status = (
"active"
if is_active
else "inactive"
)
조건이 복잡해지면 일반 if문이 읽기 쉽다.
while: 조건이 참인 동안 반복retry_count = 0
while retry_count < 3:
print(
f"{retry_count + 1}번째 시도"
)
retry_count += 1
while은 반복 횟수보다 조건이 중요한 반복에 적합하다.
while True:
command = input(
"명령어: "
)
if command == "quit":
break
True는 항상 참이므로 break가 실행될 때까지 반복한다.
break반복문을 즉시 종료한다.
logs = [
"INFO",
"INFO",
"ERROR",
"INFO",
]
for log in logs:
if log == "ERROR":
print("오류 발견")
break
continue현재 반복만 건너뛰고 다음 반복으로 이동한다.
numbers = [
3,
-1,
5,
-2,
8,
]
for number in numbers:
if number < 0:
continue
print(number)
음수는 출력되지 않는다.
for: 반복 가능한 객체 순회하기users = [
"kim",
"lee",
"park",
]
for user in users:
print(user)
for는 리스트뿐 아니라 문자열, 튜플, 딕셔너리, 집합 등 다양한 반복 가능한 객체에 사용할 수 있다.
range()숫자 범위를 만들 때 사용한다.
for number in range(5):
print(number)
0
1
2
3
4
시작값 지정:
for number in range(
1,
6,
):
print(number)
스텝 지정:
for number in range(
0,
10,
2,
):
print(number)
enumerate()인덱스와 값을 함께 사용해야 할 때 유용하다.
users = [
"kim",
"lee",
"park",
]
for index, user in enumerate(
users,
start=1,
):
print(
index,
user,
)
직접 카운터 변수를 관리하는 것보다 읽기 쉽다.
user = {
"name": "kim",
"role": "admin",
}
for key, value in user.items():
print(
key,
value,
)
matrix = [
[1, 2],
[3, 4],
]
for row in matrix:
for value in row:
print(value)
반복문 안에 다른 반복문을 넣을 수 있다.
다만 중첩이 너무 깊어지면 함수로 분리하는 것을 고려하는 편이 좋다.
elsePython에서는 for와 while에 else를 붙일 수 있다.
target = "admin"
roles = [
"user",
"editor",
]
for role in roles:
if role == target:
print("발견")
break
else:
print(
"해당 권한 없음"
)
break로 종료되지 않았을 때 else가 실행된다.
검색 로직에서 사용할 수 있다.
반복해서 새 리스트를 만드는 코드를 짧게 작성할 수 있다.
일반 반복문:
numbers = [
1,
2,
3,
4,
]
squares = []
for number in numbers:
squares.append(
number ** 2
)
컴프리헨션:
squares = [
number ** 2
for number in numbers
]
짝수만 제곱:
numbers = [
1,
2,
3,
4,
5,
6,
]
result = [
number ** 2
for number in numbers
if number % 2 == 0
]
[4, 16, 36]
조건이 복잡해지면 일반 반복문이 더 읽기 쉬울 수 있다.
users = [
"kim",
"lee",
]
name_lengths = {
user: len(user)
for user in users
}
orders = [
{
"id": 1,
"price": 12000,
"status": "paid",
},
{
"id": 2,
"price": 35000,
"status": "cancelled",
},
{
"id": 3,
"price": 42000,
"status": "paid",
},
]
결제 완료 주문 중 3만 원 이상만 처리한다.
high_value_orders = []
for order in orders:
if order["status"] != "paid":
continue
if order["price"] < 30000:
continue
high_value_orders.append(
order
)
print(high_value_orders)
조건문과 반복문이 실제 데이터 처리에서 어떻게 결합되는지 보여주는 예다.
for컬렉션의 항목을 하나씩 처리할 때 적합하다.
for user in users:
...
while특정 조건이 유지되는 동안 반복할 때 적합하다.
while retries < 3:
...
if는 조건에 따라 실행할 코드를 선택한다.elif, 기본 경로는 else로 처리한다.and, or, not을 이용해 여러 조건을 조합할 수 있다.while은 조건 기반 반복, for는 반복 가능한 객체를 순회할 때 적합하다.break는 반복 종료, continue는 현재 반복을 건너뛴다.range()는 숫자 범위 반복에, enumerate()는 인덱스와 값을 함께 사용할 때 편리하다.