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")
Run Code Copy

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 print Both x is 5 and y is 10 because both x == 5 and y == 10 are true.
  • The second if statement will also print Either x is 5 or y is 5 because x == 5 is true, even though y == 5 is false.
  • The third if statement will print x is not equal to 10 because x is not equal to 10.
Code copied to clipboard successfully 👍