Computer Science · Ch 5 — Getting Started with Python
Logical Operators
Logical Operators
Python supports three logical operators: and, or and not. They must be written in lower case only — AND or Or will not work, because Python is case-sensitive and its keywords are fixed. A logical operator evaluates to either True or False, based on the logical value of the operand(s) on either side of it.
Every value has a truth value
Before combining conditions, understand a key idea: every value in Python is logically either True or False. By default, all values count as True except:
NoneFalseitself0(zero)- empty collections — the empty string
"", the empty tuple(), the empty list[], the empty dictionary/set{} - and a few other special values
So if num1 = 10 and num2 = -20, then both num1 and num2 are logically True (any non-zero number is), while num3 = 0 is logically False. The built-in function bool() shows the truth value of anything:
>>> bool(10)
True
>>> bool(-20)
True
>>> bool(0)
False
Logical AND: and
The condition becomes True only if both operands are True.
>>> True and True
True
>>> True and False
False
>>> False and False
False
With ordinary values, the truth-value rule applies:
>>> num1 = 10
>>> num2 = -20
>>> bool(num1 and num2)
True # both non-zero, so both True
>>> num3 = 0
>>> bool(num1 and num3)
False # num3 is 0, which is logically False
Logical OR: or
The condition becomes True if any one (at least one) of the two operands is True.
>>> True or True
True
>>> True or False
True
>>> False or False
False
Again with variables:
>>> num1 = 10
>>> num3 = 0
>>> bool(num1 or num3)
True # num1 is True, so the whole condition is True
Logical NOT: not
not takes a single operand and reverses its logical state — True becomes False and False becomes True.
>>> num1 = 10
>>> bool(num1)
True
>>> not num1
False
Quick reference
| Operator | Operation | Result |
|---|---|---| …
| Operator | Operation | Description | Example (Try in Lab) |
|---|---|---|---|
| and | Logical AND | If both the operands are True, then condition becomes True | >>> True and True True >>> num1 = 10 >>> num2 = -20 >>> bool(num1 and num2) True >>> True and False False >>> num3 = 0 >>> bool(num1 and num3) False >>> False and False False |
| or | Logical OR | If any of the two operands are True, then condition becomes True | >>> True or True True >>> True or False True >>> bool(num1 or num3) True >>> False or False False |