Python에서는 if, elif('else and if'의 줄임말), else 문을 사용해서 프로그램 실행의 흐름을 제어하고 결정을 내려요.
다른 많은 프로그래밍 언어와 달리, Python 3.9 이하 버전에는 공식적인 case-switch 문이 없어요. 대신 여러 개의 elif 문으로 비슷한 역할을 해요.
Python 3.10에서는 pattern matching이라는 변형 case-switch 문이 도입되었는데, 이건 다른 개념에서 따로 다뤄요.
조건문은 True 또는 False로 귀결되는 표현식을 사용해요. bool을 직접 반환하거나, "truthy" 또는 "falsy"를 평가하는 방식이에요.
x = 10
y = 5
# The comparison '>' returns the bool 'True',
# so the statement is printed.
if x > y:
print("x is greater than y")
...
>>> x is greater than y
if와 함께 쓰면, 원래의 if 조건이 False로 평가될 때 선택적인 else 코드 블록이 실행돼요:
x = 5
y = 10
# The comparison '>' here returns the bool False,
# so the 'else' block is executed instead of the 'if' block.
if x > y:
print("x is greater than y")
else:
print("y is greater than x")
...
>>> y is greater than x
elif를 쓰면 여러 조건을 평가하고 여러 갈래로 나눌 수 있어요.
x = 5
y = 10
z = 20
# The elif statement allows for the checking of more conditions.
if x > y > z:
print("x is greater than y and z")
elif y > x > z:
print("y is greater than x and z")
else:
print("z is greater than x and y")
...
>>> z is greater than x and y
불리언 연산과 비교는 조건문과 결합해서 더 복잡한 검사에 사용할 수 있어요:
>>> def classic_fizzbuzz(number):
... if number % 3 == 0 and number % 5 == 0:
... say = 'FizzBuzz!'
... elif number % 5 == 0:
... say = 'Buzz!'
... elif number % 3 == 0:
... say = 'Fizz!'
... else:
... say = str(number)
...
... return say
>>> classic_fizzbuzz(15)
'FizzBuzz!'
>>> classic_fizzbuzz(13)
'13'
다른 방법으로, 위 예제를 if 문과 returns만 사용하도록 다시 작성할 수도 있어요.
하지만 이런 식으로 다시 쓰면 조건들이 서로 배타적이라는 점이 잘 드러나지 않을 수 있고, 나중에 버그나 유지보수 문제로 이어질 수 있어요.
>>> def classic_fizzbuzz(number):
... if number % 3 == 0 and number % 5 == 0:
... return 'FizzBuzz!'
... if number % 5 == 0:
... return 'Buzz!'
... if number % 3 == 0:
... return 'Fizz!'
...
... return str(number)
>>> classic_fizzbuzz(15)
'FizzBuzz!'
>>> classic_fizzbuzz(13)
'13'
조건문은 중첩할 수도 있어요.
>>> def driving_status(driver_age, test_score):
... if test_score >= 80:
... if 18 > driver_age >= 16:
... status = "Student driver, needs supervision."
... elif driver_age == 18:
... status = "Permitted driver, on probation."
... elif driver_age > 18:
... status = "Fully licensed driver."
... else:
... status = "Unlicensed!"
...
... return status
>>> driving_status(63, 78)
'Unlicensed!'
>>> driving_status(16, 81)
'Student driver, needs supervision.'
>>> driving_status(23, 80)
'Fully licensed driver.'
Python에는 ? 삼항 연산자가 따로 없지만, 한 줄짜리 conditional expressions를 쓸 수는 있어요.
이 표현식은 <value if True> if <conditional test> else <value if False> 형태예요.
이런 표현식은 읽기 어려워질 수 있으니, 코드를 짧게 만들고 가독성을 높이는 경우에만 이 한 줄 형태를 쓰는 게 좋아요.
>>> def just_the_buzz(number):
... return 'Buzz!' if number % 5 == 0 else str(number)
>>> just_the_buzz(15)
'Buzz!'
>>> just_the_buzz(7)
'7'
Python에서는 어떤 객체든 진리값 검사를 할 수 있어서, 조건문이나 비교, 불리언 연산에 사용할 수 있어요.
이런 식으로 평가되는 객체는 "truthy" 또는 "falsy"로 간주되며, boolean context에서 사용돼요.
>>> def truthy_test(thing):
... if thing:
... print('This is Truthy.')
... else:
... print("Nope. It's Falsy.")
# Empty container objects are considered Falsy.
>>> truthy_test([])
"Nope. It's Falsy."
>>> truthy_test(['bear', 'pig', 'giraffe'])
'This is Truthy.'
# Empty strings are considered Falsy.
>>> truthy_test('')
"Nope. It's Falsy."
>>> truthy_test('yes')
'This is Truthy.'
# 0 is also considered Falsy.
>>> truthy_test(0)
"Nope. It's Falsy."