Booleans

Python has a type bool which can take on one of two values: True and False.

1
2
3
x = True
print(x)
print(type(x))

True
<class ‘bool’>

Comparison Operations

Operation Description Operation Description
a == b a equal to b a != b a not equal to b
a < b a less than b a > b a greater than b
a <= b a less than or equal to b a >= b a greater than or equal to b

1
2
3
4
5
6
7
def can_run_for_president(age):
"""Can someone of the given age run for president in the US?"""
# The US Constitution says you must "have attained to the Age of thirty-five Years"
return age >= 35

print("Can a 19-year-old run for president?", can_run_for_president(19))
print("Can a 45-year-old run for president?", can_run_for_president(45))

Can a 19-year-old run for president? False
Can a 45-year-old run for president? True

Conditionals

While useful enough in their own right, booleans really start to shine when combined with conditional statements, using the keywords if, elif, and else.

Conditional statements, often referred to as if-then statements, allow the programmer to execute certain pieces of code depending on some Boolean condition. A basic example of a Python conditional statement is this:

1
2
3
4
5
6
7
8
9
10
11
12
def inspect(x):
if x == 0:
print(x, "is zero")
elif x > 0:
print(x, "is positive")
elif x < 0:
print(x, "is negative")
else:
print(x, "is unlike anything I've ever seen...")

inspect(0)
inspect(-15)

0 is zero
-15 is negative

Python adopts the if and else often used in other languages; its more unique keyword is elif, a contraction of “else if”. In these conditional clauses, elif and else blocks are optional; additionally, you can include as many elif statements as you would like.

Note especially the use of colons (:) and whitespace to denote separate blocks of code. This is similar to what happens when we define a function - the function header ends with :, and the following line is indented with 4 spaces. All subsequent indented lines belong to the body of the function, until we encounter an unindented line, ending the function definition.

1
2
3
4
5
6
7
8
def f(x):
if x > 0:
print("Only printed when x is positive; x =", x)
print("Also only printed when x is positive; x =", x)
print("Always printed, regardless of x's value; x =", x)

f(1)
f(0)

Only printed when x is positive; x = 1
Also only printed when x is positive; x = 1
Always printed, regardless of x’s value; x = 1
Always printed, regardless of x’s value; x = 0

Boolean conversion

We’ve seen int(), which turns things into ints, and float(), which turns things into floats, so you might not be surprised to hear that Python has a bool() function which turns things into bools.

1
2
3
4
5
6
print(bool(1)) # all numbers are treated as true, except 0
print(bool(0))
print(bool("asf")) # all strings are treated as true, except the empty string ""
print(bool(""))
# Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples)
# are "falsey" and the rest are "truthy"

True
False
True
False

We can use non-boolean objects in if conditions and other places where a boolean would be expected. Python will implicitly treat them as their corresponding boolean value:

1
2
3
4
if 0:
print(0)
elif "spam":
print("spam")

spam

Conditional expressions (aka ‘ternary’)

Setting a variable to either of two values depending on some condition is a pretty common pattern.

1
2
3
4
5
6
7
8
def quiz_message(grade):
if grade < 50:
outcome = 'failed'
else:
outcome = 'passed'
print('You', outcome, 'the quiz with a grade of', grade)

quiz_message(80)

You passed the quiz with a grade of 80

Python has a handy single-line ‘conditional expression’ syntax to simplify these cases:

1
2
3
4
5
def quiz_message(grade):
outcome = 'failed' if grade < 50 else 'passed'
print('You', outcome, 'the quiz with a grade of', grade)

quiz_message(45)

You failed the quiz with a grade of 45