Logical operators in Python can be used to combine multiple conditions and evaluate their truth value. The three main logical operators are and
, or
, and not
. They are often used to create more complex conditions and control the flow of your Python programs based on multiple criteria.
Let's see some examples of combining conditions using logical operators in Python:
# Using 'and' operator
age = 25
is_student = True
if age >= 18 and is_student:
print("You are an adult student.")
else:
print("You are either not an adult or not a student.")
# Using 'or' operator
is_raining = False
is_sunny = True
if is_raining or is_sunny:
print("The weather is either rainy or sunny.")
else:
print("The weather is neither rainy nor sunny.")
# Using 'not' operator
is_logged_in = False
if not is_logged_in:
print("Please log in to access the content.")
else:
print("Welcome! You have access to the content.")
You can also nest conditions inside each other to create more complex logic and decision-making in your Python programs.
# Using nested conditions with logical operators
age = 22
is_student = False
if age >= 18:
if is_student:
print("You are an adult student.")
else:
print("You are an adult, but not a student.")
else:
print("You are not an adult.")
# Using parentheses for clarity
x = 10
y = 20
z = 30
if (x > y) and (y < z):
print("Both conditions are true.")
else:
print("At least one condition is false.")
Combining conditions using logical operators is fundamental for creating flexible and robust Python programs that can handle various scenarios and user input effectively.