Logical Connectives
tags: #python/documentation/python_conditionals
In the context of conditional statements, logical connectives play a crucial role in forming compound conditions by combining multiple individual conditions. The commonly used logical connectives in Python are and, or, and not.
1. Conjunction: Using theand Operator
The and logical connective is used to create compound conditions that are true only if both individual conditions are true.
Truth Table
| P | Q | P AND Q |
|---|---|---|
| False | False | False |
| False | True | False |
| True | False | False |
| True | True | True |
x = 5
y = 10
if x > 0 and y > 0:
print("Both x and y are positive.")
Both x and y are positive.
2. Disjunction: Using theOR Operator
The or logical connective is used to create compound conditions that are true if at least one of the individual conditions is true.
Truth Table
| P | Q | P AND Q |
|---|---|---|
| False | False | False |
| False | True | True |
| True | False | True |
| True | True | True |
x = 5
if x < 0 or x % 2 == 0:
print("Either x is negative or x is an even number.")
Either x is negative or x is an even number.
is Falsebutx % 2 == 0is True, therefore the whole statement is True and the body of the condition will be executed.
3. Negation: Using theNOT Operator
The not logical connective is used to negate the truth value of a condition. It returns True if the condition is false and vice versa.
Truth Table
| P | Not P |
|---|---|
| False | True |
| False | True |
| True | False |
| True | False |
x = 5
if not x == 0:
print("x is not equal to zero.")
x is not equal to zero.
- X == 0 is False; not False is True
- Therefore, the statement is True, and the statement will print.