13.5. When to use And and Or¶

The keywords and, or, and not give us lots of flexibility in how we express conditions. Our goal should always be to make our code as easy as possible to understand and to avoid repeating ourselves.

One sign that you may want to use an and to simplify things, is if you have a nested if:

The inner print statement will only run if x >= 1 is true. But the if statement that checks that for that is inside if x <= 10. So it only runs if x is 10 or less. Thus to reach the message about x, it must be both 10 or less and 1 or more. So why not just write it like this?

Similarly, we could write the back check logic from the last page using multiple if statements:

But that means repeating the print statement multiple times. So the version that used or is better than this.

It is fine to chain a bunch or and or or’s together to make one large expression as shown below. This program accepts four different answers - because all four expressions are combined with or, only one part needs to be true to make the whole thing true.

Note

We could simplify the example above by using the string lower function to turn the answer into lower case: answer = answer.lower(). Once we did that, we would not have to worry about the answer being “Y” or “YES”, we would know it only had lower case letters.

We will generally stay away from more complex expressions that mix and’s and or’s, they can get confusing to write and read. If you really feel the need to write something super complex, you can use parentheses to make sure that the logic is evaluated in the right order:

# True if the type is checking or savings AND the balance is over 10000
if (balance > 10000) and (type == "checking" or type == "savings")