[Tutor] Help with 'if' statement and the concept of None

Steven D'Aprano steve at pearwood.info
Tue May 31 20:12:08 EDT 2016


On Tue, May 31, 2016 at 04:16:21PM +0100, marat murad via Tutor wrote:

> money = int(input("How many dollars do you slip the Maitr D'? "))
> *if money:*
>     print("Ah I think I can make something work")
> else:
>     print("Please sit ,it may be a while")

All values in Python can be used where a true or false boolean value is 
expected, such as in an "if" or a "while" statement. We call this a 
"boolean context", meaning something which expects a true or false flag.

So we have True and False (with the initial capital letter) as special 
constants, but we also can treat every other value as if they were true 
or false (without the initial capital). Sometimes we call them "truthy" 
and "falsey", or "true-like" and "false-like" values.

For Python built-ins, we have:

Falsey (false-like) values:

- zero: 0, 0.0, 0j, Fraction(0), etc.
- empty strings: "", b""
- empty containers: [], (), {}, set() etc.
  (empty list, empty tuple, empty dict, empty set)
- sequences with len() == 0
- None
- False

Truthy (true-like) values:

- non-zero numbers: 1, 2.0, 3j, Fraction(4, 5), etc.
- non-empty strings: "Hello world!", b"\x0"
  (yes, even the null-byte is non-empty, since it has length 1)
- non-empty containers
- sequences with len() != 0
- classes, object()
- True

We say that "false values represent nothing", like zero, empty strings, 
None, and empty containers; while "true values represent something", 
that is, anything which is not nothing.


So any time you have a value, say, x, we can test to see if x is a 
truthy or falsey value:


values = [1, 5, 0, -2.0, 3.7, None, object(), (1, 2), [], True]
for x in values:
    if x:
        print(x, "is a truthy value")
    else:
        print(x, "is a falsey value")




-- 
Steve


More information about the Tutor mailing list