Skip to main content

Section 25.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.

Checkpoint 25.5.1.

    What logic is equivalent to the logic shown below?
    if age > 12:
        if age < 20:
            print("Teenager")
    
  • if age > 12 and age < 20:
  • Correct
  • if age > 12 or age < 20:
  • To reach the print in that sample, both if’s must be True
  • if age > 12 not age < 20:
  • That does not make sense. "not" cannot combine multiple true false values
It is fine to chain a bunch of ands or ors 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 25.5.2.

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 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")
You have attempted of activities on this page.