Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python evaluates 0 as False

Tags:

python

boolean

In the Python console:

>>> a = 0
>>> if a:
...   print "L"
... 
>>> a = 1
>>> if a:
...   print "L"
... 
L
>>> a = 2
>>> if a:
...   print "L"
... 
L

Why does this happen?

like image 861
TTT Avatar asked Sep 19 '12 14:09

TTT


People also ask

Does 0 evaluate to False in Python?

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.

Is 0 == False in Python?

The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False . Understanding how Python Boolean values behave is important to programming well in Python.

Is 0 a true value in Python?

The following are falsy values in Python: The number zero ( 0 ) An empty string '' False.

What evaluates to False in Python?

First, we look at what kind of values evaluate to "True" or "False" in python. Anything that is "empty" usually evaluates to False, along with the integer 0 and the boolean value of False. Objects that are not empty evaluate to "True", along with numbers not equal to 0, and the boolean value True.


2 Answers

In Python, bool is a subclass of int, and False has the value 0; even if values weren't implicitly cast to bool in an if statement (which they are), False == 0 is true.

like image 111
Wooble Avatar answered Oct 21 '22 04:10

Wooble


0 is a falsy value in python

Falsy values: from (2.7) documentation:

zero of any numeric type, for example, 0, 0L, 0.0, 0j.

like image 37
dm03514 Avatar answered Oct 21 '22 05:10

dm03514