Combine Multiple If...
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 Multiple Conditions:
- In Python, you can combine multiple conditions in an if statement using logical operators such as
and,or, andnot.
Using and:
The
andoperator returnsTrueif both conditions it connects are true. If either condition is false, it returnsFalse.pythonif condition1 and condition2: # code to execute if both condition1 and condition2 are True
Using or:
The
oroperator returnsTrueif at least one of the conditions it connects is true. If both conditions are false, it returnsFalse.pythonif condition1 or condition2: # code to execute if either condition1 or condition2 is True
Using not:
The
notoperator negates the boolean value of the condition. It returnsTrueif the condition is false, andFalseif the condition is true.pythonif not condition: # code to execute if condition is False
Example:
Here's an example combining multiple conditions using these operators:
pythonx = 5 y = 10 if x == 5 and y == 10: print("Both x is 5 and y is 10") if x == 5 or y == 5: print("Either x is 5 or y is 5") if not (x == 10): print("x is not equal to 10")
Output:
Both x is 5 and y is 10
Either x is 5 or y is 5
x is not equal to 10
- In this code:
- The first
ifstatement will print "Both x is 5 and y is 10" because bothx == 5andy == 10are true. - The second
ifstatement will print "Either x is 5 or y is 5" becausex == 5is true, even thoughy == 5is false. - The third
ifstatement will print "x is not equal to 10" becausexis not equal to10.
- The first
Exercises:
- Using
andOperator:Write a program to check if a number is between 1 and 10 and 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 either not between 1 and 10 or it is not even.")
- Using
orOperator:Write a program to check if a number is either less than 5 or greater than 15.
pythonnumber = int(input("Enter a number: ")) if number < 5 or number > 15: print("The number is either less than 5 or greater than 15.") else: print("The number is between 5 and 15.")
- Using
notOperator:Write a program to check if a user-provided string is not empty.
pythonuser_string = input("Enter a string: ") if not user_string: print("The string is empty.") else: print("The string is not empty.")
Summary:
- Combining multiple conditions in an if-statement using
and,or, andnotallows for more complex and powerful conditional logic. Practice using these logical operators to become proficient in writing advanced if-statements in Python