Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is different in OR and AND operators in Python?
The OR and AND operators are the most commonly used logical operators in Python. These operators are used to perform decision-making operations by combining multiple conditions. In this article, we will understand what OR and AND operators are in Python and how they differ, along with examples for better understanding.
AND Operator in Python
The logical AND operator in Python needs two operands. It returns True if both operands are true, and it returns False if either of the operands is false. This operator is mostly used in situations where you want to make sure that two conditions are true at the same time.
Example of the AND Operator
The following example checks the eligibility of a person to vote. One variable has a Boolean value, and the other checks if the age is above 18 ?
age = 22
has_voter_id = True
if age >= 18 and has_voter_id:
print("You are eligible to vote.")
else:
print("Sorry, you are not eligible to vote.")
You are eligible to vote.
OR Operator in Python
The logical OR operator also needs two operands. The OR operator in Python returns True if at least one of the operands is true, and it returns False only if both operands are false. This operator is used in situations where only one condition needs to be true.
Example of OR Operator
The following example uses the OR operator to check if someone needs refreshment. If either condition is true, a message is displayed ?
is_hungry = False
is_thirsty = True
if is_hungry or is_thirsty:
print("Time for a snack or a drink!")
else:
print("All good for now!")
Time for a snack or a drink!
Key Differences
| Aspect | AND Operator | OR Operator |
|---|---|---|
| Returns True when | Both conditions are True | At least one condition is True |
| Returns False when | Any condition is False | Both conditions are False |
| Use case | All conditions must be met | Any condition can be met |
Practical Example
Here's an example showing both operators in a student grading system ?
# Student data
math_score = 85
english_score = 70
attendance = 90
# AND: Both scores must be above 80 for honors
honors = math_score > 80 and english_score > 80
print(f"Eligible for honors: {honors}")
# OR: Either high score or good attendance for pass
passed = math_score > 60 or english_score > 60 or attendance > 85
print(f"Passed the course: {passed}")
Eligible for honors: False Passed the course: True
Conclusion
The AND operator requires all conditions to be true, while the OR operator needs only one condition to be true. Use AND when all criteria must be met, and OR when any criterion can satisfy the requirement.
