Conditionals/Making Choices Using Flow Controls

4.1. Conditionals/Making Choices Using Flow Controls#

  • So far we have only written small programs that are a sequence of instructions. Sometimes you have to alter the sequential flow of a program to suit the needs of a particular situation.

4.1.1. Boolean Type#

  • Python has a built-in Boolean type called bool. Unlike int and float, which can have almost unlimited possible values, bool has only two: True and False.

4.1.2. Boolean Operators#

  • There are three basic Boolean operators: and, or, and not. not has the highest precedence, followed by and, followed by or.

Operator

What it does?

Example

and

True if both a AND b are true (logical conjunction)

if is_teacher and is_active: print(‘You can access’)

or

True if either a OR b are true (logical disjunction)

if is_superuser or (is_teacher and is active): print(‘You can access’)

not

True if the opposite of a is true (logical negation)

if not is_superuser: print(‘You cannot access’)

not True
False
not False
True
True and True
True
False and False
False
True and False
False
False and True
False
True or True
True
False or False
False
True or False
True
False or True
True
cold = True
windy = False

(not cold) and windy # It is not cold and windy
not (cold and windy) # 

4.1.3. Truthiness and Falsiness#

  • Things that are false on their own

    • None (basic data type)

    • False (basic data type)

    • Any empty sequence: '', [], ()

    • Any zero value: 0, 0.0

    • Anything whose len() returns 0

    • Empty objects

    • Everything else is True