Python or keyword

The or keyword in Python is a logical operator used to evaluate two or more conditions. It returns True if any of the conditions is True. If all conditions are False, it returns False.

Example 

is_weekend = True

is_holiday = False

if is_weekend or is_holiday:

    print("You can relax today!")

Output:

You can relax today!

Syntax

condition1 or condition2
  • condition1 and condition2: Boolean expressions to evaluate.

The or operator:

  • Returns True if at least one of the conditions evaluates to True.
  • Returns False only if all conditions are False.

Why Use or?

  1. Combine Multiple Conditions: Allows checking multiple criteria where at least one must be True.
  2. Simplify Decision-Making: Reduces complexity by combining related conditions.
  3. Flexible Logic: Enables alternative actions when one of several conditions is met.

Common Examples

1. Checking Multiple Conditions

age = 20

is_student = True

if age < 18 or is_student:

    print("Discount available")

Output:

Discount available

2. Default Fallback Using or

username = ""

default_username = "Guest"

final_username = username or default_username

print(final_username)

Output:

Guest

3. Using or in User Input Validation

response = input("Enter yes or y to continue: ").lower()

if response == "yes" or response == "y":

    print("You chose to continue!")

else:

    print("You chose not to continue!")

4. Combining or with not

has_access = False

is_admin = True

if not has_access or is_admin:

    print("Access granted to admin")

Output:

Access granted to admin

5. Checking Membership

fruit = "apple"

if fruit == "apple" or fruit == "banana":

    print("The fruit is either apple or banana")

Output:

The fruit is either apple or banana

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top