조건문(Conditional Statement)
개요
Python에서 조건문은 프로그램의 흐름을 제어하기 위해 사용되는 구문입니다.
조건문을 통해 특정 조건에 따라 다른 작업을 실행할 수 있습니다.
Python의 조건문에는 주로 if, elif, else 키워드가 사용됩니다.

if – elseif – else 문
if 문은 주어진 조건이 참(True)일 때 코드 블록을 실행합니다.
elif는 이전 조건이 거짓일 때 새로운 조건을 평가합니다. 여러 조건을 순차적으로 검사할 때 사용됩니다.
else는 위의 모든 조건이 거짓일 때 실행되는 코드 블록을 정의합니다.
예제
다음과 같이 나이(age)에 따라 확인하는 조건문을 작성합니다.
18세 이상은 성인, 13세 ~ 17세는 청소년, 12세 이하는 어린이를 출력하게 하는 함수를 정의합니다.
def checkAge(age):
if age >= 18:
print("He is an adult.")
elif age >= 13:
print("He is a teenager.")
else:
print("He is a child.")나이를 파라미터로 전달하여 결과를 확인합니다.
checkAge(20) checkAge(15) checkAge(5)
결과
He is an adult. He is a teenager. He is a child.
조건문의 중첩(Nested Conditionals)
조건문 내에 또 다른 조건문을 사용하는 것을 ‘중첩(Nested Conditional)’이라고 합니다.
조건문의 중첩은 코드의 가독성을 떨어뜨리고 로직을 복잡하게 만들 수 있습니다.
가능하면 중첩 사용을 최소화하고, 함수를 활용하여 코드를 모듈화하는 것이 좋습니다.
복수 개의 조건 (Multiple conditions in if)
and, or, not와 같은 불린 연산자를 활용하여 복잡한 조건을 간결하게 표현할 수 있습니다.
특히, 여러 조건을 한 번에 검사해야 할 때 유용합니다.
예제
나이가 18세 이상이고, 권한을 가지고 있을 때 접근을 허용하는 조건문은 다음과 같습니다.
age = 20
has_permission = True
if age >= 18 and has_permission:
print("Allow access")
else:
print("Deny access")결과
Allow access
in 연산자와 함께 사용하기
멤버십 연산자 in은 특정 값이 시퀀스(리스트, 튜플, 문자열 등) 내에 존재하는지 확인할 때 사용됩니다.
조건문과 함께 사용하면 코드를 더욱 간결하게 만들 수 있습니다.
예제
대상 과일(fruit)이 먹는 것이 허용된 과일 목록에 포함되어 있는지 확인하는 조건문 입니다.
allowed_fruits = ["Apple", "Banana", "Cherry"]
fruit = "Apple"
if fruit in allowed_fruits:
print(f"{fruit}is allowed to eat.")
else:
print(f"{fruit}is not allowed to eat.")결과
Appleis allowed to eat.
match 문 (Python 3.10 이상)
Python 3.10에서는 새로운 구조적 패턴 매칭 기능인 match 문이 도입되었습니다.
- 구조적 패턴 매칭: 값 뿐만 아니라 데이터 타입, 데이터 구조까지도 패턴을 매칭하여 비교하는 검사
이는 다양한 가능한 케이스를 보다 간결하고 명확하게 처리할 수 있게 해줍니다
예제
다음과 같이 리스트 패턴 매칭을 구현 할 수 있습니다.
def handle_list(items):
match items:
case []:
print("Empty list.")
case [first]:
print(f"There is only one item in list: {first}")
case [first, second]:
print(f"There are two items in list: {first}, {second}")
case [first, *rest]:
print(f"first item: {first}, rest: {rest}")
handle_list([])
handle_list(["Apple"])
handle_list(["Apple", "Banana"])
handle_list(["Apple", "Banana", "Cherry"]) 결과
Empty list. There is only one item in list: Apple There are two items in list: Apple, Banana first item: Apple, rest: ['Banana', 'Cherry']
예제
다음과 같이 match 문법의 case 구문에는 if를 활용하여 추가적인 조건을 명시할 수 있습니다.
다음은 int 타입이고 양의 정수인지 음의 정수인지 정수가 아닌 지를 판별하는 조건문 예시입니다.
# Guard pattern matching
def handle_number(number):
match number:
case int() as x if x > 0:
print(f"{x} is positive integer.")
case int() as x if x < 0:
print(f"{x} is negative integer.")
case _:
print(f"{number} is not integer.")
handle_number(10)
handle_number(-5)
handle_number(3.14) 결과
10 is positive integer. -5 is negative integer. 3.14 is not integer.
반복문(Loop Statements)
개요
Python에서 반복문은 코드 블록을 반복적으로 실행할 수 있게 해주는 구조입니다.
Python에서는 주로 두 가지 유형의 반복문을 사용합니다: for 반복문과 while 반복문입니다
for 반복문
반복문은 시퀀스(리스트, 튜플, 딕셔너리, 문자열 등)를 순회하며, 시퀀스의 각 요소에 대해 코드 블록을 실행합니다.
for
for 반복문은 주로 정해진 횟수만큼 반복하거나, 컬렉션의 모든 요소를 처리할 때 사용됩니다.
예제
리스트에 있는 과일 목록 반복문을 통해 확인하여 출력합니다.
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
print(fruit)결과
Apple Banana Cherry
while 반복문
while 반복문은 주어진 조건이 참(True)인 동안 코드 블록을 반복적으로 실행합니다.
조건이 거짓(False)이 되는 순간 반복이 멈춥니다.
예제
특정 문구(Python is funny.)를 3회 반복 출력합니다.
i = 0
while i < 3:
print("Python is funny.")
i += 1결과
Python is funny. Python is funny. Python is funny.
반복문 제어
반복문을 더 효율적으로 제어하기 위한 몇 가지 키워드가 있습니다:
break: 현재 실행 중인 반복문을 즉시 종료합니다.continue: 현재 반복을 건너뛰고 반복문의 다음 순회(iteration)를 계속합니다.else:for또는while반복문이 중간에break로 종료되지 않고 끝까지 실행됐을 때 한 번 더 실행되는 블록입니다.
break 예제
break를 이용하여 num이 5가 되면 반복문을 종료합니다.
# break example
for num in range(1, 10):
if num == 5:
print("Breaking at", num)
break
print("Current number is", num)결과
Current number is 1 Current number is 2 Current number is 3 Current number is 4 Breaking at 5
continue 예제
짝수는 continue 하여 아래 를 진행하지 않고 다음으로 넘어갑니다.
print("\nUsing continue")
for num in range(1, 10):
if num % 2 == 0:
continue
print("Odd number", num)결과
Using continue Odd number 1 Odd number 3 Odd number 5 Odd number 7 Odd number 9
for:else 예제
num이 5가 되어 반복문을 종료할 때, else: 문을 한번 수행하고 반복문을 종료됩니다.
print("\nUsing else with loops")
for num in range(1, 5):
print("Number is", num)
else:
print("Loop finished without a break")결과
Using else with loops Number is 1 Number is 2 Number is 3 Number is 4 Loop finished without a break
index 함께 사용하여 반복문 수행하기 ( enumerate() 사용 )
반복문을 사용할 때, 인덱스와 함께 요소를 순회하고 싶을 때 enumerate() 함수를 사용합니다.
이는 반복 가능한 객체를 인덱스와 요소의 쌍으로 반복할 수 있게 해줍니다.
예제
fruits = ["Apple", "Banana", "Cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)결과
0 Apple 1 Banana 2 Cherry
두 개 이상의 객체 동시 순회 ( zip() 사용 )
두 개 이상의 반복 가능한 객체를 동시에 순회하고 싶을 때 zip() 함수를 사용합니다.
zip()은 여러 반복 가능한 객체들을 튜플의 형태로 묶어줍니다.
예제
이름(names)과 나이(ages) 두 리스트를 반복하며 순회하며 tuple 형태로 묶어 출력합니다.
names = ["Jin", "Kim", "Lee"]
ages = [20, 30, 40]
for name, age in zip(names, ages):
print(f"{name} is {age}.")결과
Jin is 20. Kim is 30. Lee is 40.
참고 문헌
- “Think Python: How to Think Like a Computer Scientist”
- Python Conditional and Loop
- My Git Repository (devitworld-python-basic) – 2_function.ipynb









