Logical Operators
Sometimes we need to compare multiple things to make a determination about which path to follow.
For example, let's say I want to see a movie. I have a child with me, so I can't see a PG-13 or R-rated movie. I don't have enough money for a 3D film, so that selection is out. And it is the weekend, so all the first run movies are sold out; I am limited to movies which have been in the theater for a while. This is a complicated scenario that looks at several things at once.
I can use logical operators to string several things together at once.
There are three logical operators in Python: and,
or, and not. The semantics (meaning) of these
operators is similar to their meaning in English.
and
Just as in English, and in Python looks at two scenarios. In other for the
entire statement to evaluate as true, both scenarios have to true. x and
y returns False if x is False, otherwise it
returns evaluation of y.
| Code | Output | Notes |
|---|---|---|
x = False |
False |
The only way this evaluates as true is when BOTH In this case, Python will not evaluate y since it knows that the left
hand side of the ‘and’ expression is |
x = 3 |
True |
We know |
x = 15 |
False |
While it is true that 15 is greater than 0, 15 is not less than 10.
Since |
How would this look in a conditional statement?
| Code | Evaluates As |
|---|---|
x = False |
false |
x = 3 |
true |
x = 15 |
false |
or
Once again Python looks at two scenarios but this one acts a little
differently. If one or both of the scenarios is true, then the entire
statement will evaluate to true. If x is True, it returns True,
else it returns evaluation of y.
| Code | Output | Notes |
|---|---|---|
x = False |
True |
This evaluates as true is when EITHER Short-circuit evaluation applies here as well. If |
x = 3 |
True |
We know |
x = -10 |
True |
Negative 10 is not greater than 0, so Python looks at the second scenario. -10 is less than 10, so the entire statement evaluates as true. |
x = 3 |
False |
3 is not less than or equal to 2, so the first scenario evaluates as false. 3 is also not greater than 5. Since both scenarios evaluate as false, the entire statement is false. |
How would this look in a conditional statement?
| Code | Output |
|---|---|
x = False |
true |
x = 3 |
true |
x = -10 |
true |
x = 3 |
false |
not
The not operator negates a boolean expression – or does the
opposite, so not (x > y) is True if x > y is False, that is, if x is less
than or equal to y.
| Code | Output | Notes |
|---|---|---|
x = True |
False |
If |
x = 4 |
True |
Look from the inside, out. Inside, we have |
How would this look in a conditional statement?
| Code | Output |
|---|---|
x = True |
false |
x = 4 |
true |
Simplifying Nested Conditionals
Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:
if 0 < x: if x < 10:
print('x is a positive
single-digit number.')
The print statement runs only if we make it past both conditionals, so we can
get the same effect with the and operator:
if 0 < x and
x < 10: print('x is a positive single-digit
number.')
For this kind of condition, Python provides a more concise option:
if 0 < x < 10: print('x is a
positive single-digit number.')
Using Logical Operators with non-Boolean Objects
Strictly speaking, the operands of the logical operators should be Boolean expressions, but Python is not very strict. Any nonzero number is interpreted as True:
>>> 42 and True True
This flexibility can be useful, but there are some subtleties to it that might be confusing. You might want to avoid it (unless you know what you are doing).
Using Parenthesis in Conditional Statements
When you use multiple logical operators, it can be helpful – more readable and less prone to error – to group them together using parenthesis:
| Example |
|---|
if (x and y): |
if (x > 0) and (x < 10): |
if (color1=="blue") and (color2=="green" or
color2=="purple"): |
if not (color1=="blue" or
color1=="red"): |
Example: Number Guessing
In this program, we take guesses from the user and check if it is the number that we have.
number = 23 guess = int(input('Enter an integer: ')) if
guess == number: # New block starts here
print('You guessed it!') # New
block ends here elif guess < number: # Another block
print('No, you are too low!') else:
# you must have guessed > number to reach here
print('No, you are too high!') print('Done') # This
last statement is always executed, # after the if statement is executed.
Output:
First Execution:
Enter an integer : 50 No, it is a little lower than that Done
Second Execution:
Enter an integer : 22 No, it is a little higher than that Done
Third Execution:
Enter an integer : 23 Congratulations, you guessed it. (but you do not win any prizes!) Done
How It Works
| Code | Output | Notes |
|---|---|---|
number = 23 |
None |
First, we assign the literal constant value |
guess = int(input('Enter an integer: ')) |
Enter an integer: |
Next, we use the Note: if the user enters non-numerals, such as the word "Hi" then the program will throw a Runtime error when trying to convert it to an integer. |
if guess == number: |
You guessed it! |
Next, we compare the guess of the user with the number we have chosen. If they are equal, we print a success message. Notice that we use indentation levels to tell Python which statements belong to which block. This is why indentation is so important in Python. I hope you are sticking to the "consistent indentation" rule. Are you? Notice how the |
elif guess < number: |
No, you are too low! |
Then, we check if the guess is less than the number, and if so, we
inform the user that they must guess a little higher than that. What we
have used here is the |
else: |
No, you are too high! |
Finally, if We could also have written this as elif guess >
number:
but using |
print('Done') |
Done |
After Python has finished executing the complete |
Even though this is a very simple program, I have been pointing out a lot of things that you should notice. All these are pretty straightforward (and surprisingly simple for those of you from C/C++ backgrounds). You will need to become aware of all these things initially, but after some practice you will become comfortable with them, and it will all feel 'natural' to you.
