Skip to content

Python if statement or operator | Examples code

  • by

Python “OR” operator will use in the if statement to test conditions and decide which execution path your programs will take.

A if statement with or operator in Python

Simple python example code using “OR” logical operator that evaluates as True if any of the operands is True.

An example of an OR operator

Use python or logical operator to form a compound logical expression. OR logical operator returns True if any of the operands provided to it evaluates to true.

Taking input value from the user in this example.

x = int(input('Enter your age: '))

if x < 21 or x > 100:
    print('You are too young or too old, go away!')
else:
    print('Welcome, you are of the right age!')

Output:

Python if statement or operator

Using multiple OR operator example

Example how to evaluate more than two expressions by using the OR operator.

a = 'Text'
b = 33
c = 'Python'

if (a == 'Text') or (b == 20) or (c == 'Python'):
    print("True")
else:
    print("All are False")

Output:

True

Example ‘OR’ with ‘AND’ operator

See a Python example code of using the ‘and’ and ‘or’ operators in if statement.

a = 5
b = 10
c = 15
d = 20

if (a > 0 or b == 15) and (c == 16 or d == 20):
    print("True")
else:
    print("False")

Output:

True

Here’s a summary of the Python or operator’s behavior:

Result of exp1Result of exp2Result of exp1 or exp2
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Do comment if you have any doubts and suggestions on this Python code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading