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
y = True
x and y
False

The only way this evaluates as true is when BOTH x and y are True. Since x is False, this entire statement evaluates to false.

In this case, Python will not evaluate y since it knows that the left hand side of the ‘and’ expression is False which implies that the whole expression will be False irrespective of the other values. This is called short-circuit evaluation.

x = 3
x > 0 and x < 10
True

We know x = 3. 3 is greater than 0 and 3 is less than 10, so this evaluates to true.

x = 15
x > 0 and x < 10
False

While it is true that 15 is greater than 0, 15 is not less than 10. Since x < 10 is false, then the entire statement evaluates as false.

How would this look in a conditional statement?

Code Evaluates As
x = False
y = True
if x and y:
    print("true")
else:
    print("false")
false
x = 3
if x > 0 and x < 10:
    print("true")
else:
    print("false")
true
x = 15
if x > 0 and x < 10:
    print("true")
else:
    print("false")
false

Launch Exercise

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
y = True
x or y
True

This evaluates as true is when EITHER x and y are True. Since x is False, then Python looks at y. Since y is True, then this entire statement evaluates to true.

Short-circuit evaluation applies here as well. If x had evaluated as true, then Python would not have bothered to evalute y. and the entire statement would evaluate as true.

x = 3
x > 0 or x < 10
True

We know x = 3. 3 is greater than 0, so Python would stop right there and evaluate this to true.

x = -10
x > 0 or 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
x <= 2 or x > 5
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
y = True
if x or y:
    print("true")
else:
    print("false")
true
x = 3
if x > 0 or x < 10:
    print("true")
else:
    print("false")
true
x = -10
if x > 0 or x < 10:
    print("true")
else:
    print("false")
true
x = 3
if x <= 2 or x > 5:
    print("true")
else:
    print("false")
false

Launch Exercise

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
not x
False

If x = True, then the opposite of True is False. So not x is the same as saying not True, which is False. So not x evaluates to False.

x = 4
y = 5
not x > y
True

Look from the inside, out. Inside, we have x > y. 4 is not greater than 5, so x > y evaluates as false. But then we have not (False). The opposite of False is True, so the entire statement evaluates as True.

How would this look in a conditional statement?

Code Output
x = True
if not x:
    print("true")
else:
    print("false")
false
x = 4
y = 5
if not x > y:
    print("true")
else:
    print("false")
true

Launch Exercise

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.')

Launch Exercise

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"):

Launch Exercise

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 23 to the variable number using the assignment operator (=).

guess = int(input('Enter an integer: ')) Enter an integer:

Next, we use the input statement to ask the user to enter a number. We also use the int statement to convert the input to an integer. We assign this integer to the variable guess and continues.

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:
    # New block starts here
    print('You guessed it!')
    # New block ends here
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 if statement contains a colon at the end - we are indicating to Python that a block of statements follows.

elif guess < number:
    # Another block
    print('No, you are too low!')  
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 elif clause which actually combines two related if else-if else statements into one combined if-elif-else statement. This makes the program easier and reduces the amount of indentation required.

else:
    # you must have guessed >
    # number to reach here
    print('No, you are too high!')
No, you are too high!

Finally, if guess is not equal to number and guess is not less than number, then we use the else clause to tell them they picked a number which was too large.

We could also have written this as

elif guess > number:

but using else accomplished the same thing.

print('Done')
# This last statement is always executed,
# after the if statement is executed.
Done

After Python has finished executing the complete if statement along with the associated elif and else clauses, it moves on to the next statement in the block containing the if statement. In this case, it is the main block (where execution of the program starts), and the next statement is the print('Done') statement. After this, Python sees the ends of the program and simply finishes up.

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.