mass = 3.54
if mass > 3.0:
print(mass, 'is large')
mass = 2.07
if mass > 3.0:
print (mass, 'is large')3.54 is large
if, else, elif를 사용하여 프로그램의 흐름을 제어하는 코드를 작성할 수 있습니다.if 문을 사용한 실행 제어if 문은 특정 조건(conditional)을 만족할 때만 코드가 실행되도록 제어합니다.for 루프와 유사합니다.
if로 시작하여 조건식을 적고 콜론(:)으로 끝냅니다.mass = 3.54
if mass > 3.0:
print(mass, 'is large')
mass = 2.07
if mass > 3.0:
print (mass, 'is large')3.54 is large
masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for m in masses:
if m > 3.0:
print(m, 'is large')3.54 is large
9.22 is large
else를 사용한 예외 처리else 구문은 if 문 뒤에 위치하며, 조건이 거짓(not true)일 때 실행할 대안 코드(alternative)를 지정합니다.masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for m in masses:
if m > 3.0:
print(m, 'is large')
else:
print(m, 'is small')3.54 is large
2.07 is small
9.22 is large
1.86 is small
1.71 is small
elif를 사용한 다중 조건 판단elif(“else if”의 약자)를 사용합니다.elif는 항상 if 문 뒤에 오며, 여러 번 사용할 수 있습니다.else는 모든 조건에 해당하지 않는 경우를 위해 가장 마지막에 위치해야 합니다.masses = [3.54, 2.07, 9.22, 1.86, 1.71]
for m in masses:
if m > 9.0:
print(m, 'is HUGE')
elif m > 3.0:
print(m, 'is large')
else:
print(m, 'is small')3.54 is large
2.07 is small
9.22 is HUGE
1.86 is small
1.71 is small
grade = 85
if grade >= 90:
print('grade is A')
elif grade >= 80:
print('grade is B')
elif grade >= 70:
print('grade is C')grade is B
velocity = 10.0
if velocity > 20.0:
print('moving too fast')
else:
print('adjusting velocity')
velocity = 50.0adjusting velocity
velocity = 10.0
for i in range(5):
print(i, ':', velocity)
if velocity > 20.0:
print('moving too fast')
velocity = velocity - 5.0
else:
print('moving too slow')
velocity = velocity + 10.0
print('final velocity:', velocity)0 : 10.0
moving too slow
1 : 20.0
moving too slow
2 : 30.0
moving too fast
3 : 25.0
moving too fast
4 : 20.0
moving too slow
final velocity: 30.0
프로그램의 동작을 이해하려면 시간에 따른 변수의 변화를 표(table)로 그려보는 것이 좋습니다.
| i | 0 | 1 | 2 | 3 | 4 |
| velocity | 10.0 | 20.0 | 30.0 | 25.0 | 20.0 |
and, or 및 괄호를 활용한 복합 조건식
여러 조건을 동시에 만족해야 하거나 하나만 만족해도 되는 경우 and(그리고)와 or(또는) 논리 연산자를 사용합니다.
mass = [ 3.54, 2.07, 9.22, 1.86, 1.71]
velocity = [10.00, 20.00, 30.00, 25.00, 20.00]
for i in range(5):
if mass[i] > 5 and velocity[i] > 20:
print("Fast heavy object.")
elif mass[i] > 2 and mass[i] <= 5 and velocity[i] <= 20:
print("Normal traffic")
elif mass[i] <= 2 and velocity[i] <= 20:
print("Slow light object.")
else:
print("Check the data.")Normal traffic
Normal traffic
Fast heavy object.
Check the data.
Slow light object.
조건이 복잡해질 때는 소괄호 ()를 사용하여 우선순위를 명확히 하는 것이 좋습니다. and와 or가 혼용될 때는 괄호를 사용하여 의도를 분명히 밝히세요.
if (mass[i] <= 2 or mass[i] >= 5) and velocity[i] > 20:
# (질량이 2 이하이거나 5 이상인 경우)이면서 속도가 20 초과인 경우Cell In[9], line 2 # (질량이 2 이하이거나 5 이상인 경우)이면서 속도가 20 초과인 경우 ^ SyntaxError: incomplete input
다음 코드의 출력값은 무엇일까요?
pressure = 71.9
if pressure > 50.0:
pressure = 25.0
elif pressure <= 50.0:
pressure = 0.0
print(pressure)25.0 (첫 번째 if 조건이 참이 되어 실행된 후 전체 조건문을 빠져나옵니다.)
음수인 값은 0으로, 양수(0 포함)인 값은 1로 변환하여 새로운 리스트를 만드는 코드를 완성하세요.
original = [-1.5, 0.2, 0.4, 0.0, -1.3, 0.4]
result = []
for value in original:
if value < 0.0:
result.append(0)
else:
result.append(1)
print(result)리스트에서 최솟값과 최댓값을 찾는 다음 코드를 완성하세요. None을 활용하여 초기화하는 방법에 유의하세요.
values = [-2, 1, 65, 78, -54, -24, 100]
smallest, largest = None, None
for v in values:
if smallest is None or v < smallest:
smallest = v
if largest is None or v > largest:
largest = v
print(smallest, largest)참고: 파이썬에서는 == None보다 is None을 사용하는 것을 권장합니다. 또한, 실제로는 내장 함수 min()과 max()를 사용하는 것이 가장 효율적입니다.
if 문을 사용하여 코드 블록의 실행 여부를 제어합니다.else는 조건이 거짓일 때 실행할 코드를 지정합니다.elif는 여러 개의 조건을 순차적으로 검사할 때 사용합니다.