How to combine multiple conditions in an if-statement in Python?
Combine Multiple Conditions in an If-statement
In Python, you can combine multiple conditions in an if
statement using logical operators such as and
, or
, and not
. Here's a brief overview of how you can use these operators:
Using and
: The and
operator returns True
if both conditions it connects are true. If either condition is false, it returns False
.
if condition1 and condition2:
# code to execute if both condition1 and condition2 are True
Using or
: The or
operator returns True
if at least one of the conditions it connects is true. If both conditions are false, it returns False
.
if condition1 or condition2:
# code to execute if either condition1 or condition2 is True
Using not
: The not
operator negates the boolean value of the condition. It returns True
if the condition is false, and False
if the condition is true.
if not condition:
# code to execute if condition is False
Example
Here's an example combining multiple conditions using these operators:
Python Program
x = 5
y = 10
if x == 5 and y == 10:
print("Both x is 5 and y is 10")
if x == 5 or y == 5:
print("Either x is 5 or y is 5")
if not (x == 10):
print("x is not equal to 10")
Output
Both x is 5 and y is 10
Either x is 5 or y is 5
x is not equal to 10
In this code:
- The first
if
statement will printBoth x is 5 and y is 10
because bothx == 5
andy == 10
are true. - The second
if
statement will also printEither x is 5 or y is 5
becausex == 5
is true, even thoughy == 5
is false. - The third
if
statement will printx is not equal to 10
becausex
is not equal to 10.