Python의 조건문은 코드 흐름을 분기 시키는 기본 도구입니다. 들여쓰기를 통해 조건에 따라 실행 블록을 구분합니다.
Python
if 조건식:
실행문
python
score = 85
if score >= 60:
print("합격입니다")
else :
print("불합격입니다.")
python
score = 75
if score >= 90:
print("A등급")
elif score >= 80:
print("B등급")
elif score >= 70:
print("C등급")
else:
print("D등급")
elif는 필요에 따라 여러 번 사용 가능합니다.
else는 모든 조건이 False일 때 실행됩니다.
python
num = 10
if num > 0:
if num % 2 == 0:
print("양수이며 짝수입니다.")
else:
print("양수이며 홀술입니다.")
else:
print("0 또는 음수입니다.")
반복문은 같은 코드를 여러 번 실행할 때 사용됩니다.
시퀸스(list, tuple, dict, str 등)의 각 요소를 순회합니다.
python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
python
for ch in "Python":
print(ch)
python
person = {"name": "Alice", "age": 30}
for key in person:
print(key, ":", person[key])
python
for i in range(5): # 0부터 4까지
print(i)
for i in range(1, 6): # 1부터 5까지
print(i)
for i in range(10, 0, -2): # 10부터 2까지 2씩 감소
print(i)
python
count = 0
while count < 5:
print("count:", count)
count += 1
python
for i in range(10):
if i == 5:
break
print(i) # 0 ~ 4까지 출력
python
for i in range(5):
if i == 2:
continue
print(i) # 0, 1, 3, 4 출력 (2는 제외)
python
for i in range(5):
if i == 2:
pass # 이후 구현 예정
print(i)
python
def feature_coming_soon():
pass
이번 편에서는 Python의 코드 흐름을 제어하는 조건문과 반복문, 그리고 흐름 제어 키워드 들을 알아봤습니다.
다음 편에서는 함수와 매개변수, 반환값에 대해 학습해보겠습니다.