VMware ESXi and vSphere Cluster Management
Use Logical Operators in Python
Learn how Python's and, or, and not logical operators combine Boolean conditions in if, elif, and else statements.
Logical operators combine or alter Boolean conditions. A Boolean is a value that is either True or False. A comparison operator, such as <, >=, or ==, produces a Boolean result.
For example, age >= 21 is either True or False. Logical operators let one conditional statement use several comparisons.
age = 25
if age >= 21 and age <= 100:
print("Age is allowed")
Python provides three logical operators: and, or, and not. They can be used in if, elif, and conditional expressions.
Python logical operators
| Operator | Left condition | Right condition | Result |
|---|---|---|---|
and | False | False | False |
and | False | True | False |
and | True | False | False |
and | True | True | True |
or | False | False | False |
or | False | True | True |
or | True | False | True |
or | True | True | True |
not | True | Not applicable | False |
not | False | Not applicable | True |
The and operator
and is true only when every connected condition is true. It is useful when all requirements must be satisfied, such as checking that a number is inside a range.
age = 30
if age > 20 and age < 40:
print("Young adult")
Both comparisons must be true. The value must be greater than 20 and less than 40. Therefore, 30 matches, but 20 and 40 do not.
For inclusive boundaries, use >= and <=:
if age >= 21 and age <= 39:
print("Age is from 21 through 39")
The or operator
or is true when at least one connected condition is true. Both operands may be true, but only one needs to be true for the complete expression to be true.
Use or to detect values outside an allowed range:
if age < 21 or age > 100:
print("Age is outside the allowed range")
An age of 14 satisfies the first comparison. An age of 101 satisfies the second. An age cannot normally be both below 21 and above 100, but or would still produce True if both operands were true in another situation.
The not operator
not reverses the truth value of an expression: not True becomes False, and not False becomes True.
is_valid = False
if not is_valid:
print("Reject the value")
if not (age >= minimum and age <= maximum):
print("Age is not within the approved range")
This is useful when the action is based on rejecting a condition that is not acceptable, such as a user who is not logged in or a value that is not in an approved range.
Logical operators in if, elif, and else
A conditional statement selects code based on conditions. Python evaluates an if/elif/else chain from top to bottom and executes the first branch whose condition is true. The else branch handles every remaining case after the earlier conditions are false.
score = 82
if score >= 90:
print("Excellent")
elif score >= 70 and score < 90:
print("Good")
else:
print("Keep practicing")
Once the elif condition matches, Python skips the remaining branches. This matters when more than one condition could appear valid: only the first matching branch in the chain runs.
Age-range validation example
The following program reads text with input(), converts it to an integer with int(), and rejects ages below 21 or above 100. The else branch accepts the inclusive interval from 21 through 100.
age = int(input("Enter your age: "))
if age < 21 or age > 100:
print("Rejected: age must be from 21 through 100.")
else:
print("Accepted: age is within the permitted range.")
| Entered age | Relevant condition | Boolean outcome | Selected branch | Expected message category |
|---|---|---|---|---|
| 14 | age < 21 | True | if | Rejected below minimum |
| 25 | age < 21 or age > 100 | False | else | Accepted in range |
| 101 | age > 100 | True | if | Rejected above maximum |
| 21 | age < 21 or age > 100 | False | else | Accepted at lower boundary |
| 100 | age < 21 or age > 100 | False | else | Accepted at upper boundary |
Multiple age categories
Several age bands can be written with and. An initial invalid-value branch uses or. The final else is a fallback for values not covered by the chosen boundaries.
age = int(input("Enter your age: "))
if age < 0 or age > 100:
print("Implausible age")
elif 0 <= age <= 12:
print("Child")
elif 13 <= age <= 20:
print("Teenager")
elif 21 <= age <= 39:
print("Young adult")
elif 40 <= age <= 59:
print("Middle-age adult")
elif 60 <= age <= 100:
print("Older adult")
else:
print("Age was not assigned to a category")
Inputs such as 12, 25, 58, and 68 select the child, young-adult, middle-age, and older-adult categories. Inputs of -6 and 105 select the implausible-age branch. In this particular design, every integer from 0 through 100 is covered, so the final fallback is defensive and documents what should happen if the boundaries are changed later.
Range boundaries and comparison correctness
A range is a span of values between lower and upper limits. An inclusive boundary includes an endpoint with >= or <=. An exclusive boundary excludes an endpoint with > or <.
| Expression | Lower endpoint included | Upper endpoint included | Example use |
|---|---|---|---|
age > 0 and age < 21 | No | No | Only values 1 through 20 when age is an integer |
age >= 0 and age <= 20 | Yes | Yes | Inclusive ages 0 through 20 |
0 <= age <= 20 | Yes | Yes | Clear chained-comparison form |
21 <= age <= 39 | Yes | Yes | Inclusive ages 21 through 39 |
The condition age > 0 and age < 21 excludes both 0 and 21. If adjacent categories use age > 0 and age < 21 followed by age > 21 and age < 40, the values 21 and 40 can be left uncovered. Choose endpoint rules deliberately.
Python's chained comparison syntax is often clearer:
if 21 <= age <= 39:
print("Age is from 21 through 39")
This means the same as age >= 21 and age <= 39. It does not mean that Python compares two Boolean results; it expresses that one value is between two bounds.
Operator precedence and grouping
When operators are mixed, Python applies them in this order: not has higher precedence than and, and and has higher precedence than or. Parentheses should be used whenever the intended grouping is not immediately obvious.
# Without parentheses, and is evaluated before or
if is_admin or is_editor and account_is_active:
print("Access may be allowed")
# Explicitly require an active account for either role
if (is_admin or is_editor) and account_is_active:
print("Access may be allowed")
The parenthesized version is safer to read and easier to modify. Parentheses are especially important in validation rules combining alternative cases:
if (age < 0 or age > 100) or not has_permission:
print("Reject request")
Short-circuit evaluation
Short-circuit evaluation means Python stops checking a logical expression once its final result is known. With and, a false left operand is enough to make the whole expression false. With or, a true left operand is enough to make the whole expression true.
This behavior can prevent unsafe operations. Check that a value is present before comparing it with a number:
value = None
if value is not None and value > 10:
print("Value is greater than 10")
If value is not None is false, Python does not evaluate value > 10, so it avoids comparing None with an integer. Put the safety check on the left side of and.
Input limitations
Range checking and input-format validation are separate tasks. The expression age < 21 or age > 100 checks a numeric range, but int(input(...)) must first successfully convert the entered text to an integer.
If the user enters letters such as twenty, int() raises a ValueError before the range condition can run. A try/except block is the next step toward robust input handling:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a whole number.")
else:
if age < 21 or age > 100:
print("Age is outside the allowed range.")
else:
print("Age accepted.")
Troubleshooting logical conditions
- An exact boundary reaches the fallback: strict comparisons may exclude values such as 21 or 40. Decide whether endpoints are inclusive and ensure adjacent ranges meet.
- A condition is unexpectedly true: mixed
andandormay be grouped differently from your intention. Add parentheses and test each smaller comparison independently. - Letters cause a failure:
int()cannot convert non-numeric text. CatchValueErroror validate the format before conversion. - Only one category message prints: an
if/elifchain executes only its first true branch. Order branches from specific to general, or use separateifstatements when actions are independent. - A comparison with an optional value raises an error: check for
Nonefirst, as invalue is not None and value > limit.
Key points
- Logical operators combine Boolean conditions or reverse a Boolean result.
- Use
andwhen all requirements must be true. - Use
orwhen at least one alternative can be true. - Use
notto test the opposite of a condition. - Use inclusive comparisons deliberately, especially at adjacent range boundaries.
- Use chained comparisons such as
21 <= age <= 39for readable range checks. - Remember that
notbinds more tightly thanand, andandmore tightly thanor; add parentheses when grouping matters. - Remember that an
if/elif/elsechain runs only the first matching branch.
Continue with Use Logical Operators.