Python: Booleans and Conditionals
Booleans
Python has a type bool which can take on one of two values: True and False.
1 | x = True |
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 | def can_run_for_president(age): |
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 | def inspect(x): |
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 | def f(x): |
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 | print(bool(1)) # all numbers are treated as true, except 0 |
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 | if 0: |
spam
Conditional expressions (aka ‘ternary’)
Setting a variable to either of two values depending on some condition is a pretty common pattern.
1 | def quiz_message(grade): |
You passed the quiz with a grade of 80
Python has a handy single-line ‘conditional expression’ syntax to simplify these cases:
1 | def quiz_message(grade): |
You failed the quiz with a grade of 45