-
[파이썬] 5. 조건문 if / elif/ else파이썬 Python 2019. 11. 25. 19:28
# 조건문 (condition)
- 특정 조건을 만족하는 경우에만 수행할 작업이 있을 때 사용.
- 모든 조건은 boolean으로 표현 됨 (예외사항 있음)
- if, elif, else 키워드 사용
- 콜론 (:)을 통해 블록을 만들어줌.
if 6 >= 5: print ('6 is greater than 5') print ('Yeah, it is true') #들여쓰기 내에서 if 가 적용 받음 if 6 == 5: print('6 is greater than 5') print ('This code is not belongs to if statements') # if 문과 관계 없는 코드
결과값 #조건문의 논리식
- AND, OR, NOT을 이용
- AND
- T AND T : T
- T AND F : F
- F AND T : F
- F AND F : F
- OR
- T OR T : T
- T OR F : T
- F OR T : T
- F OR F : F
- NOT
- NOT T : F
- NOT F : T
- NOT
- NOT T : F
- NOT F : T
- 우선순위
- NOT > AND > OR
a = 10 b = 8 c = 11 if a == 10 or b == 9: print('that is true') #T if a == 10 and b != 9: print('that is true') #T if a == 10 or b == 9 and c == 12: print('that is true') #T if(a == 10 or b==9) and c == 12: print('that is ture') #F if not a == 10: print('a is 10') #F
#if의 조건이 boolean 타입이 아닌 경우
- 일반적으로 조건문에는 bool이 주로 위치함
- 하지만 정수, 실수, 문자열, 리스트 등 기본 타입도 조건에 사용 가능
- false로 간주되는 값 (각 타입의 기본값)
- None
- 0
- 0.0
- "
- [] : 빈 리스트
- (): 빈 튜플
- {}: 빈 딕셔너리
- set(): 빈 집합
- 그밖의 모든 값은 True 로 간주 됨
a = 0 b = 10 if 3.5: print('3 3333') #T if a: print ('print') #F if b: print ('print') #T # if 조건이 false로 간주되는 기본 값외에는 다 true 라고 가정
# if, else
- if가 아닌 경우, 나머지 조건을 표현하고 싶을 때 바로 아래 else 블럭 사용.
- if 조건이 true 인 경우 if 블락 코드 수행, 거짓인 경우 else 블럭 코드 수행
#짝수인 경우에는 2로 나눈 값을 출력 하고 #홀수인 경우에는 1을 더한 값을 출력해라 a = 11 if a % 2 == 0: # 짝수인지 판별 print(a / 2) else: print(a +1) #12
# if, elif, else
- 조건이 여러개인 경우 if와 else 사이에 elif 블록 사용
a = 17 if a % 4 == 0: print ('a is divisible by 4') elif a % 4 == 1: print ('a % 4 is 1') elif a % 4 == 2: print ('a % 4 is 2') else: print ('a % 4 is 3') # a % 4 is 1
a = 17 if a % 4 == 0: print ('a is divisible by 4') if a % 4 == 1: print ('a % 4 is 1') if a % 4 == 2: print ('a % 4 is 2') else: print ('a % 4 is 3') #a % 4 is 1 #a % 4 is 3 #두가지 라인이 출력됨
# 중첩조건문 (nested condition)
- 조건문의 경우 중첩 가능
- 중첩의 의미는 depth로 생각할 수 있으며, 제한은 없음
a = 10 b = 9 c = 8 if a == 10: if c == 8: if b == 8: print ('a is ten and b is 8') else: print ('a is ten and b is not 8') if a == 10: if c == 9: if b == 9: print ('a is ten and b is 8') else: print ('a is ten and b is not 8') else: print ('a is 10 and c is not 9') # a is ten and b is not 8 # a is 10 and c is not 9
반응형'파이썬 Python' 카테고리의 다른 글
[파이썬] 7. 파이썬 함수 정의와 호출 - 함수의 parameter, return (함수 파라미터와 리턴) (0) 2019.12.04 [파이썬] 6. 반복문 while / for 의 이해 (feat. break와 continue) (1) 2019.11.25 [파이썬] 4. 컬렉션 타입의 이해 - 파이썬 dictionary 와 set (0) 2019.11.18 [파이썬] 3. 컬렉션 타입의 이해 - 리스트(list)와 튜플 (tuple) (0) 2019.11.18 [파이썬] 2. 문자열 사용방법 (feat. 이스케이프 문자 / index / slicing / 문자열 함수) (0) 2019.11.16