JGerulskis
JGerulskis

Reputation: 808

Why does a single value work as a condition

Obviously, in conditional statements you need to make sure a true or false value is returned to either execute or skip the block of code associated with the if statement. How does a single value serve as a true Boolean in python? I'm not sure if this is a universal for all languages but I've discovered it in python 3.x.

Example:

value = 1
if value:
   print("value == True") # prints every time

I'd expect the compiler to complain or just return false. Why does the compiler perceive if value as true?

Upvotes: 1

Views: 263

Answers (1)

Marcin
Marcin

Reputation: 238071

Integer or floats values other than 0 are treated as True:

In [8]: bool(int(1))
Out[8]: True

In [9]: bool(int(0))
Out[9]: False

In [10]: bool(int(-1))
Out[10]: True


In [16]: bool(float(1.2e4))
Out[16]: True

In [17]: bool(float(-1.4))
Out[17]: True

In [20]: bool(0.0)
Out[20]: False

In [21]: bool(0.000001)
Out[21]: True

Similarly, empty lists, sets, dicts, empty string, None, etc are treated as false:

In [11]: bool([])
Out[11]: False

In [12]: bool({})
Out[12]: False

In [13]: bool(set())
Out[13]: False

In [14]: bool("")
Out[14]: False

In [19]: bool(None)
Out[19]: False

Upvotes: 5

Related Questions