조건문(IF문)
if <조건문1>:
<조건문1이 True일 때 실행할 문장>
elif <조건문2>:
<조건문1이 False 이고 조건문2가 True일 때 실행할 문장>
else:
<조건문1과 조건문2가 모두 False일 때 실행할 문장>
파이썬 조건문(IF)이란 참과 거짓을 판단하는 문장을 말한다. 비교연산자(==, >, <, !=, >=, <=
), 논리연산자(and, or, not
) 그리고 in/not 연산자를 이용하여 조건문을 표현한다.in
연산자는 튜플/리스트/문자열 안에 특정 값이 있는지를 확인하는 연산자이며 있으면 True, 없으면 False를 반환한다.
print(1 in [1,2,3])
print(1 in ['1', '2', '3'])
print('a' not in ('a', 'b'))
True
False
False
money = True
if money:
print('택시를 타라')
else:
print('걸어가라')
택시를 타라
money = 2000
if money >= 3000:
print('택시를 타세요')
else:
print('걸어가세요')
걸어가세요
money = 2000
card = True
if money >= 3000 or card:
print('택시를 타세요')
else:
print('걸어가세요')
택시를 타세요
pocket = ['paper', 'cellphone', 'money']
if 'money' in pocket:
print('택시를 타라')
else:
print('걸어가라')
택시를 타라
pocket = ['paper', 'handphone']
card = True
if 'money' in pocket:
print('택시를 타라')
elif card:
print('카드로 결제')
else:
print('걸어가라')
카드로 결제
조건문을 만족하면서 아무것도 실행하지 않고자 할 때 pass
를 사용한다.
pocket = ['paper', 'cellphone', 'money']
if 'money' in pocket:
pass
else:
print('카드를 꺼내')
조건부표현식
조건문이 참인 경우
if 조건문
else 조건문이 거짓인 경인 경우
조건부표현식을 사용하여 if문을 간단하게 표현할 수 있다.
if score >= 60:
message = "success"
else:
message = "failure"
message = "success" if score >= 60 else "failure"
반응형
'Python' 카테고리의 다른 글
[Python] range() 함수 (120) | 2024.01.16 |
---|---|
[Python] 반복문 (81) | 2024.01.15 |
[Python] 불(bool) 자료형 (76) | 2024.01.11 |
[python] 튜플(tuple) (72) | 2024.01.10 |
[Python] 집합 자료형 함수 (54) | 2024.01.09 |
댓글