Hit enter after type your search item

Python or operator

The ‘or’ in Python is a logical operator that evaluates as True if any of the operands is True, unlike the ‘and’ operator where all operands have to be True.

An OR example  ‘and’ ‘or’ example

For example, if we check x == 10 and y == 20 in the if condition. If either of the expression is True, the code inside the if statement will execute. This is demonstrated in the example below.

An example of OR operator

In the following example, the value of variable int_x = 10 and int_y = 20. The values of these variables are checked in the if statement with OR operator.

See online demo and code

or operator

Even the value of int_y is not less than 20 and it is False, still the if statement evaluated True so the statement inside if statement executed.

User input example with OR operator

For this example, the value for x and y variables are taken by the user input.

If the value of x >= 10 or y <= 20, the if statement should evaluate as True. I have entered three different set of values and see the output:

See online demo and code

Python or

So, How OR operator works?

For understanding the concept of OR operator, have a look at the following example. Suppose we have (x or y).

The OR operator will only evaluate the y if x is False. If x was True, it will not check y.

In the case of AND operator, if x is True, it will evaluate y. If x is False then y will not be evaluated.

See this demonstration in the code below:

See online demo and code

or concept

Hope it clears how Python OR operator works.

Using multiple OR operator example

You may evaluate more than two expressions by using the OR operator. For demonstrating this, I have declared and assigned values to three variables.

The OR operator is used twice in the if statement to evaluate three expressions. If either of the three expressions is True, the print function inside the if statement should display the message.

If all are False, the statement in the else block should execute:

See online demo and code

or multiple

You can see, only one expression out of three is True, so the if statement is True.

A Demo of ‘or’ and ‘and’ operator

Can we use the ‘or’ and ‘and’ operator in single if statement and if it works? Yes, we may use it depending on the scenario.

See an example of using the ‘and’ and ‘or’ operators in single if statement.

See online demo and code

and or

In that case, both OR operators must be true to make if statement True. If one is True and the other is False, the ‘AND’ operator evaluates as False.

So if variable values are a=5, b= 10, c = 15, d= 20 then:

(a == 5 or b == 15) and (c == 16 or d == 20) = True

(a == 5 or b == 15) and (c == 16 or d == 21) = False

(a == 10 or b == 15) and (c == 16 or d == 20) = True

(a == 8 or b == 13) and (c == 15 or d == 20) = False

This div height required for enabling the sticky sidebar