Combining Conditions for More Powerful Decisions
In programming, there are often situations where you need to check more than one condition at the same time.
In such cases, using compound conditions allows you to combine multiple conditions to implement more complex logical decisions easily.
In this lesson, we will learn about compound conditions using and
and or
.
What are Compound Conditions?
Compound conditions refer to combining multiple conditions into a single condition.
In Python, you can create compound conditions using the and
and or
operators.
True Only When All Conditions are True: and
The overall condition is True only when all sub-conditions are true.
This logical operation is known as logical conjunction
.
x = 10
y = 20
if x > 5 and y < 30: # Check if x is greater than 5 and at the same time y is less than 30
print("x is greater than 5, and y is less than 30")
In the code above, the condition x > 5 and y < 30
is true only if both sub-conditions are met.
If the value of x is less than or equal to 5 or the value of y is greater than or equal to 30, the if condition will be false.
True If At Least One Condition is True: or
The overall condition is True if at least one sub-condition is true.
This logical operation is known as logical disjunction
.
x = 10
y = 20
if x > 5 or y > 30: # Check if x is greater than 5 or y is greater than 30
print("x is greater than 5, or y is greater than 30")
In the code above, the condition x > 5 or y > 30
is true if at least one of the sub-conditions is met.
Hence, if the value of x is less than or equal to 5 and the value of y is less than or equal to 30, the if condition will be false.
Examples of Conditional Statements Using Various Compound Conditions
Let's assume we are writing a program that offers a special discount only if the user is at least 18 years old and a member.
age = 20 # Age
is_member = True # Membership status
# Check if the user is at least 18 years old and at the same time a member
if age >= 18 and is_member:
print("You are eligible for a special discount.")
else:
print("You are not eligible for a special discount.")
Here, the condition age >= 18 and is_member
is true only if both conditions are met.
Therefore, when the user is at least 18 years old and is a member, the message "You are eligible for a special discount." is printed.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.