If AND
Introduction:
- Python supports the usual logical conditions from mathematics:
- Equals:
a == b - Not Equals:
a != b - Less than:
a < b - Less than or equal to:
a <= b - Greater than:
a > b - Greater than or equal to:
a >= b
- Equals:
Combining Conditions with AND:
- You can combine multiple conditions into a single expression in Python conditional statements like
if,if-else, andelifstatements using theANDlogical operator. This helps avoid writing multiple nestedifstatements unnecessarily.
Examples:
- Python If with AND Operator:
Using the
ANDoperator to combine two boolean conditions.pythona = 5 b = 2 # Nested if if a == 5: if b > 0: print('a is 5 and', b, 'is greater than zero.') # OR you can combine the conditions as if a == 5 and b > 0: print('a is 5 and', b, 'is greater than zero.')Output:
a is 5 and 2 is greater than zero. a is 5 and 2 is greater than zero.
- Python If-Else with AND Operator:
Combining two basic conditional expressions in the boolean expression of a Python
if-elsestatement.pythona = 3 b = 2 if a == 5 and b > 0: print('a is 5 and', b, 'is greater than zero.') else: print('a is not 5 or', b, 'is not greater than zero.')Output:
a is not 5 or 2 is not greater than zero.
- Python Elif with AND Operator:
Combining two basic conditional expressions in the boolean expression of a Python
elifstatement.pythona = 8 if a < 0: print('a is less than zero.') elif a > 0 and a < 8: print('a is in (0.8)') elif a > 7 and a < 15: print('a is in (7.15)')Output:
a is in (7.15)
Exercises:
- If with AND Operator:
Write a program to check if a number is between 1 and 10 and if it is even.
pythonnumber = int(input("Enter a number: ")) if number > 1 and number < 10 and number % 2 == 0: print("The number is between 1 and 10 and is even.") else: print("The number is not between 1 and 10 or it is not even.")
- If-Else with AND Operator:
Write a program to check if a user is a teenager (age between 13 and 19) and if they have permission.
pythonage = int(input("Enter age: ")) has_permission = input("Do you have permission (yes/no): ").lower() == 'yes' if age >= 13 and age <= 19 and has_permission: print("You are a teenager with permission.") else: print("You are either not a teenager or do not have permission.")
Summary:
- In this tutorial, we learned how to use the Python
ANDlogical operator with Python conditional statements (if,if-else,elif). Practice using these operators to become proficient in forming compound logical expressions in your programs