언어 Language/파이썬 Python

Q. 파이썬에서는 어떤 값들이 False일까?

Tap to restart 2022. 12. 30. 18:00
반응형

A. 0, '', (), [], {}, set(), range(0), None 등이 False다.


공식 문서 설명은 다음과 같다.

constants defined to be false: None and False.
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)

출처: Truth Value Testing, Python Documentation

아래 값들은 모두 False다.

bool(0)
bool('')
bool(())
bool([])
bool({})
bool(set())
bool(range(0))
bool(None)
bool(False)


어떤 값들이 False인지 알아두는 것은 엄청 중요하다.
코드를 짜다보면 True, False로 나눠서 처리하는 경우가 많기 때문이다.

a = None인 경우 한번 여러가지 형태로 if 문을 실행해보자.

a = None
if a is None:
    print("a is None")

if a:
    print("if a")
else:
    print("if a else")

if bool(a) is False:
    print("bool(a) is False")
    
if a is False:
    print("a is False")

if not a:
    print("if not a")

어떤 결과가 나올 것인가?

출력 결과는 다음과 같다.

a is None
if a else
bool(a) is False
if not a

여기서 주의할 점은 if a is False의 경우는 출력되지 않는다. a 자체는 None이므로, bool(a)가 False이므로. if not a로 해야 한다. a가 False인데 not이라 뒤집혀서 True가 되므로.

반응형