Python If Condition with OR Operator - Examples


Python If OR

You can combine multiple conditions into a single expression in an If statement, If-Else statement, or Elif statement using the logical operator OR.

The Python OR logical operator returns True if at least one of the two operands is True. For more details on the syntax and truth table, refer to the Python OR logical operator tutorial.


Examples

In the following examples, we will explore how we can use the Python OR logical operator to form compound conditions in conditional statements.


1. Python If with OR operator in condition

In this example, we will use the Python or operator to join two simple boolean conditions into a compound boolean condition in a Python If statement.

Python Program

today = 'Saturday'

if today=='Sunday' or today=='Saturday':
	print('Today is off. Rest at home.')

Explanation:

The conditions today=='Sunday' and today=='Saturday' are simple boolean conditions. Using the OR operator, we combine them to form the compound condition: today=='Sunday' or today=='Saturday'. If either of the conditions evaluates to True, the message is printed.

Output

Today is off. Rest at home.

2. Python If-Else with OR operator in condition

In this example, we use the or operator to combine two basic conditional expressions in the boolean expression of a Python If-Else statement.

Python Program

today = 'Wednesday'

if today=='Sunday' or today=='Saturday':
	print('Today is off. Rest at home.')
else:
	print('Go to work.')

Explanation:

Here, the OR operator combines the two conditions: today=='Sunday' and today=='Saturday'. Since neither condition evaluates to True (today is 'Wednesday'), the else block is executed, resulting in the message: Go to work.

Output

Go to work.

3. Python Elif with OR operator in condition

In this example, we use the or operator to combine two conditional expressions in the boolean expression of a Python Elif statement.

Python Program

today = 'Sunday'

if today=='Monday':
	print('Your weekend is over. Go to work.')
elif today=='Sunday' or today=='Saturday':
	print('Today is off.')
else:
	print('Go to work.')

Explanation:

Here, the first condition checks if today is 'Monday'. Since it is not, we proceed to the elif condition. Using the OR operator, we check if today is either 'Sunday' or 'Saturday'. Since today is 'Sunday', the message Today is off. is printed.

Output

Today is off.

Summary

In this tutorial, we learned how to use the Python OR logical operator in If, If-Else, and Elif conditional statements. The OR operator allows us to combine multiple conditions into one, executing a block of code if at least one condition is True.




Python Libraries