Course Content
Introduction to Python
Introduction to Python
How to Combine Conditions in Python
In Boolean logic, two fundamental operators are OR and AND. The OR operator returns True
if at least one of the conditions is true; otherwise, it returns False
. The AND operator returns True
only if both conditions are true; otherwise, it returns False
. You can combine conditions using the and
and or
operators (always in lowercase)
condition1 and condition2
yieldsTrue
only when both conditions areTrue
;condition1 or condition2
givesTrue
if at least one condition isTrue
.
Note
You can also chain multiple conditions using these operators. Use parentheses to make the order of operations clear.
For example, consider the following conditions:
- Whether
2
is greater than1
and"bbb"
is different from"aaa"
. - Whether the character at 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')
The first print()
returns True
since both 2 > 1
and 'bbb' != 'aaa'
are true. The second print()
outputs False
because the character at index 2
is neither 'y'
nor 's'
(it's actually a space).
Note
To reverse a boolean value, use the
not
operator. For example,not 1 == 1
results inFalse
because1 == 1
isTrue
, andnot
negates it toFalse
..
Thanks for your feedback!