← 输入框|python.land|刷新

Python Boolean and Conditional Programming: if.. else

Besides numbers and strings, Python has several other types of data. One of them is the Boolean data type. Booleans are extremely simple: they are either true or false. Booleans, in combination with Boolean operators, make it possible to create conditional programs: programs that decide to do different things, based on certain conditions.

The Boolean data type was named after George Boole, the man that defined an algebraic system of logic in the mid 19th century.

What is a Boolean?

Let’s start with a definition:

Boolean
A boolean is the simplest data type; it’s either True or False.

In computer science, booleans are used a lot. This has to do with how computers work internally. Many operations inside a computer come down to a simple “true or false.” It’s important to note, that in Python a Boolean value starts with an upper-case letter: True or False. This is in contrast to most other programming languages, where lower-case is the norm.

In Python, we use booleans in combination with conditional statements to control the flow of a program:

>>> door_is_locked = True
>>> if door_is_locked:
...     print("Mum, open the door!")
...
Mum, open the door!
Code language: Python (python)

First, we define a variable called door_is_locked and set it to True. Next, you’ll find an if-statement. This is a so-called conditional statement. It is followed by an expression that can evaluate to either True or False. If the expression evaluates to True, the block of code that follows is executed. If it evaluates to False, it is skipped. Go ahead and change door_is_locked to False in the REPL to see what happens.

An if can be followed by an optional else block. This block is executed only when the expression evaluates to False. This way, you can run code for both options. Let’s try this:

>>> door_is_locked = False
>>> if door_is_locked:
...     print("Mum, open the door!")
... else:
...     print("Let's go inside")
...
Let's go inside
Code language: Python (python)

Thanks to our else-block, we can now print an alternative text if door_is_locked is False. As an exercise, try to modify the first code example above to get the same result.

If, elif and else

Often there are more than two options. For that, Python has elif, which is short for “else if.” You can add as many elif blocks as you need between the if and the optional else:

temperature = 18

if temperature > 25:
    print("It's hot, wear shorts")
elif temperature > 15:
    print("Nice weather, a T-shirt will do")
elif temperature > 5:
    print("Bring a jacket")
else:
    print("It's cold, wear a coat")Code language: Python (python)

This prints:

Nice weather, a T-shirt will doCode language: Python (python)

Python checks the conditions from top to bottom and runs only the first block whose condition is True. All the others are skipped, even if their condition would be true as well. With a temperature of 18, both temperature > 15 and temperature > 5 are true, but only the T-shirt line gets printed. That’s why the order of your conditions matters: start with the most specific one. If none of the conditions is true, the else block runs.

Python operators

The ability to use conditions is what makes computers tick; they make your software smart and allow it to change its behavior based on external input. We’ve used True directly so far, but more expressions evaluate to either True or False. These expressions often include a so-called operator.

There are multiple types of operators, and for now, we’ll only look at these:

  1. Comparison operators: they compare two values to each other
  2. Logical operators

Comparison operators

Let’s look at comparison operators first. You can play around with them in the REPL:

>>> 2 > 1
True
>>> 2 < 1
False
>>> 2 < 3 < 4 < 5 < 6
True
>>> 2 < 3 > 2
True
>>> 3 <= 3
True
>>> 3 >= 2
True
>>> 2 == 2
True
>>> 4 != 5
True
>>> 'a' == 'a'
True
>>> 'a' > 'b'
FalseCode language: Python (python)

This is what all the comparison operators are called:

OperatorMeaning
>greater than
<smaller than
>=greater than or equal to
<=smaller than or equal to
==is equal
!=is not equal
Python’s comparison operators

As can be seen in the examples, these operators work on strings too. Strings are compared in the order of the alphabet, with these added rules:

  • Uppercase letters are ‘smaller’ than lowercase letters, e.g.: ‘M’ < ‘m’
  • Digits are smaller than letters: ‘1’ < ‘a’

You’re probably wondering what the logic is behind these rules. Internally, each character has a number in a table. The position in this table determines the order. It’s as simple as that. See Unicode on Wikipedia to learn more about it if you’re interested.

Want to put these comparisons into practice? Try the Python comparison exercise in your browser for free. Compare values and see when Python produces True or False.

Logical operators

Next up: logical operators. You use them to combine conditions, like “the door is locked and nobody is home.” The following table lists and describes them. The arrow shows what each expression evaluates to:

OperatorWhat it doesExamples
andTrue if both statements are trueTrue and False → False
False and False → False
True and True → True
orTrue if one of the statements is trueTrue or False → True
True or True → True
False or False → False
notNegates the statement that followsnot True → False
not False → True
Python logical operators

Here are some examples in the REPL to help you play around with these:

>>> not True
False
>>> not False
True
>>> True and True
True
>>> True and False
FalseCode language: Python (python)

Be careful when you mix logical operators with comparisons. Comparison operators like == are evaluated first, so False and False == False means False and (False == False), which is False. Use parentheses when in doubt: (False and False) == False gives True.

Truthy and falsy values

An if statement doesn’t need an actual boolean. You can give it any value, and Python decides whether that value counts as true or false. Values that count as false are called falsy:

  • False and None
  • the number zero: 0 and 0.0
  • empty collections: an empty string "", an empty list [], an empty dictionary {}, and so on

Everything else is truthy. You can check what Python thinks of a value with the bool() function:

>>> bool(0)
False
>>> bool("")
False
>>> bool([])
False
>>> bool(None)
False
>>> bool(-3)
True
>>> bool("hello")
True
>>> bool([0])
TrueCode language: Python (python)

Note the last one: a list containing a zero is not empty, so it’s truthy. This lets you write short, readable checks like this one:

shopping_list = []

if shopping_list:
    print("Let's go shopping")
else:
    print("Nothing to buy")Code language: Python (python)

The logical operators work with truthiness too, and they don’t always return True or False. Instead, and and or return one of the two values you gave them. or returns the first value if it’s truthy and otherwise the second. and returns the first value if it’s falsy and otherwise the second:

>>> "" or "default"
'default'
>>> "Erik" or "default"
'Erik'
>>> 0 and 5
0
>>> 3 and 5
5Code language: Python (python)

You’ll see the or trick a lot to provide a default value, for example name = user_input or "anonymous".

Comparing different types in Python

When you try to compare different types, you’ll often get an error. Let’s say you want to compare an integer with a string:

>>> 1 < 'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'
>>>Code language: Python (python)

This is how Python tells you it can’t compare integers to strings. But there are types that can mix and match. I would recommend against it because it makes your code hard to understand, but for sake of demonstration, let’s compare a boolean and an int:

>>> True == 1
True
>>> False == 0
True
>>> True + True
2
>>> False + False
0
>>> False + True
1
>>> True + 3
4
>>>Code language: Python (python)

As can be seen, True has a value of 1, and False has a value of 0. This has to do with the internal representation of booleans in Python: they are a special kind of number in Python.

The match statement

Since Python 3.10, there’s another way to choose between options: the match statement. It compares one value against a list of patterns and runs the block of the first case that matches. When you compare a single variable against a handful of fixed values, it often reads better than a long chain of elif blocks:

command = "go"

match command:
    case "start" | "go":
        print("Starting...")
    case "stop":
        print("Stopping")
    case _:
        print("Unknown command:", command)Code language: Python (python)

This prints Starting.... Change command to "jump" and you’ll get Unknown command: jump instead.

A few things to notice:

  • The | lets one case match several values: “start” or “go”.
  • case _ matches anything. It works like the else of an if-statement, so put it last.
  • Only the first matching case runs. There’s no fall-through to the next case, as in the switch statement of some other languages.

The match statement can do a lot more, like taking apart lists, dictionaries and objects. That’s called structural pattern matching, and the official pattern matching tutorial (PEP 636) explains it well. For everyday decisions, if, elif and else are still what you’ll use most.

Related articles

4 thoughts on “Python Boolean and Conditional Programming: if.. else”

  1. I love it that you included the info and link on George Boole.
    It’s not necessary to know, but it fills in naturally occurring questions which helps to keep one’s mind from wandering and wondering. And he deserves the exposure, considering his contribution to modern computing.

Leave a Comment