
Python Bool 알아보기
# chapter03-7
# 불(bool) 자료형
# 참(True) / 거짓(False)만을 나타내는 자료형
# 조건문, 반복문에서 자주 사용됨
# 선언
a = True
b = False
print(type(a), a) # <class 'bool'> True
print(type(b), b) # <class 'bool'> False
print()
# 예제 1 : 숫자에서 bool 판정
print(bool(1)) # True (0이 아닌 숫자는 True)
print(bool(0)) # False (0은 False)
print(bool(-1)) # True (음수도 True)
print()
# 예제 2 : 문자열에서 bool 판정
print(bool("python")) # True (내용이 있는 문자열은 True)
print(bool("")) # False (빈 문자열은 False)
print()
# 예제 3 : 리스트, 튜플, 딕셔너리, 집합
print(bool([1, 2, 3])) # True (요소가 있으면 True)
print(bool([])) # False (빈 리스트는 False)
print(bool((0,))) # True (요소 1개라도 있으면 True)
print(bool(())) # False (빈 튜플은 False)
print(bool({'a': 1})) # True (딕셔너리에 요소 있으면 True)
print(bool({})) # False (빈 딕셔너리는 False)
print(bool(set([1]))) # True
print(bool(set())) # False (빈 집합은 False)
print()
# 예제 4 : 조건문에서 활용
x = [1, 2, 3]
y = []
if x:
print("x 리스트는 비어있지 않음") # 출력됨
if not y:
print("y 리스트는 비어있음") # 출력됨