Open In App

Python if OR

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, if statement is the conditional statement that allow us to run certain code only if a specific condition is true . By combining it with OR operator, we can check if any one of multiple conditions is true, giving us more control over our program.

Example: This program check whether the no is positive or even.

Python
a = 4
if a > 0 or a % 2 == 0:
    print("True")
else:
    print("False")

Output
True

We can use the if with OR operator in many ways. Let's understand each one, step by step.

Compare Strings

The most common use case of an if statement with the OR operator is to check if a string matches any of several possible values.

Let's understand this with simple example.

Python
a = "python"
if a == "python" or a == "java":
    print("Selected")

Output
Selected

Explanation:

  • Checks if a is "python" or "java".
  • Prints "Selected" if true.

To validate User Input

We can also used to check if the user's input is valid by matching it with predefined options.

Example:

Python
s= "python"
if s == "python" or s == "java" :
    print("Valid ")
else:
    print("Unvalid")

Explanation:

  • This code checks if the input s is either "python" or "java".
  • If true, it prints "Valid", otherwise it prints "Unvalid".

Handling Multiple False Conditions

We can use if with or to check if one condition is true, even if the others aren't.

Example:

Python
a = False # task1
b = True #task2
if  a or  b:
   print("one task completed.")
else:
   print("No tasks are completed.")

Output
one task completed.

Explanation:

  • This code checks if either a or b is true.
  • As b is true, it prints "one task completed"

Using OR with Comparison Operators

We can also use OR statement with comparison operators to check multiple conditions.

Example:

Python
a = 25
if a < 18 or a > 60:
    print("Ineligible")
else:
    print("Eligible")

Output
Eligible

Explanation:

  • This code checks if a is outside the range 18-60.
  • As a is 25, it prints "Eligible".

Next Article
Article Tags :
Practice Tags :

Similar Reads