Python Advanced Conditions
Advanced Conditions
This page covers the advanced conditions of Python programming.
For Python intermediate conditions here.
It continues the previous intermediate conditions tutorial in more details. Python advanced conditions encompass:
- logical operators(and, or, and not)
- membership operators (in and not in)
- identity operators (is and is not)
Operators
Operators are mathematical operations that perform interact with variables and values.
This tutorial covers logical operators, membership operators, and identity operators.
These types of operators work well with conditional statements.
Logical operators
There are three types of logical operators:
- and (outcome True: if two or more statements are true)
- or (outcome True: if one or more statements are true)
- not (outcome False: if statements are true)
1. And
a = 4 b = 7 if a > 2 and b > 3: print("Both conditions are true.") # Output: Both conditions are true.
If one of the conditions is not true, the “if” statement will not produce the message.
2. Or
a = 1 b = 7 if a > 2 or b > 3: print("At least one condition is true.") # Output: At least one condition is true.
Although one of the conditions is not true, the “if” statement still produces the message.
3. Not
The keyword “not” reverses the output, if True the result becomes False.
a = 3 if not(a > 2): print("Just a message.") # Output:
The above variable “a” is more than 2, which makes the condition True. But keyword “not” reverses it to False, so the “if” statement does not display the message.
Let’s do the opposite.
a = 1 if not(a > 2): print("Just a message.") # Output: Just a message.
The variable is now less than 2, which is makes the condition false. But the keyword “not” reverses it to True. so the message prints out.
Membership operators
There are two types of membership operators:
- in (outcome True: if item or value inside object)
- not in (outcome True: if item or value not inside object)
1. In
a = "This is a test message." if "test" in a: print("The word 'test' is present.") # Output: The word 'test' is present.
If “test” is not in the variable “a”, the message will not display.
2. Not in
a = ["red", "blue", "purple"] if "yellow" not in a: print("Yellow is not present.") # Output: Yellow is not present.
If “yellow” is inside the list “a”, the message will not print out.
Identity operators
There are two types of identity operators:
- is (outcome True: if two objects are equal)
- is not (outcome True: if two objects are not equal)
1. Is
a = 14 b = 14 if a is b: print("a equals b") # Output: a equals b
If the values of “a” and “b” are different, the message will not appear.
2. Is not
a = 14 b = 9 if a is not b: print("a does not equal b") # Output: a does not equal b
If variable “a” and “b” are equal, the message will not display.
Next: Python Advanced Loops