Course Content
Introduction to Python
Introduction to Python
Combining Conditions
In Boolean logic, two fundamental operators are OR and AND. What do they represent?
The OR operator checks if either of the conditions is true and returns True
if so; otherwise, it returns False
.
The AND operator ensures both conditions are true before returning True
. If not, it returns False
.
In Python, to combine conditions, use the and
& or
operators (always in lowercase).
For example:
condition1 and condition2
yieldsTrue
only when both conditions areTrue
;condition1 or condition2
givesTrue
if at least one condition isTrue
.
Note
You can also chain more than two conditions using these operators. Employ parentheses to clarify the order of operations.
As an illustration, consider these conditions:
- Whether
2
exceeds1
and if"bbb"
isn't the same as"aaa"
; - If the character with index
2
in the string"my string"
is either"y"
or"s"
.
# Check the first two conditions print(2 > 1 and "bbb" != "aaa") # Check the next two conditions print("my string"[2] == "y" or "my string"[2] == "s")
How should we interpret the outcomes? The initial print()
issues a True
response since both 2 > 1
and "bbb" != "aaa"
hold true. The following print()
yields False
because the character at index 2
is neither 'y'
nor 's'
(it's actually a space).
Note
If you wish to reverse a boolean value, employ the
not
operator. For instance,not 1 == 1
results inFalse
because1 == 1
isTrue
, and we've negated that toFalse
.
Thanks for your feedback!