Python 3 – Logical Operators Example
Python 3 is a powerful programming language that comes with built-in operators to perform logical operations. These logical operators are used to evaluate different conditions and allow us to perform actions based on whether the condition is true or false. Logical operators allow us to combine multiple conditions to create more complex conditions.
Logical Operators in Python 3:
AND Operator:
The AND operator is a binary operator that returns True if both operands are true, otherwise, it returns False. The syntax of the AND operator in Python 3 is as follows:
x and y
The above code returns True if both x and y are true, otherwise, it returns False.
Example:
a = 10
b = 20
c = 30
if a > 5 and b < 25 and c == 30:
print("All conditions are True.")
else:
print("At least one condition is False.")
The output of the above code will be “All conditions are True.” because all the conditions are true.
OR Operator:
The OR operator is another binary operator in Python 3 that returns True if either of the operands is true, otherwise, it returns False. The syntax of the OR operator in Python 3 is as follows:
x or y
The above code returns True if either x or y is true, otherwise, it returns False.
Example:
a = 10
b = 20
c = 30
if a > 5 or b < 15 or c == 40:
print("At least one condition is True.")
else:
print("All conditions are False.")
The output of the above code will be “At least one condition is True.” because the first condition is true.
NOT Operator:
The NOT operator is a unary operator in Python 3 that returns the opposite of the operand’s current boolean value. The syntax of the NOT operator in Python 3 is as follows:
not x
The above code returns True if x is False, otherwise, it returns False.
Example:
a = 10
b = 20
if not a > 5:
print("a is not greater than 5.")
else:
print("a is greater than 5.")
if not b < 15:
print("b is not less than 15.")
else:
print("b is less than 15.")
The output of the above code will be:
a is greater than 5.
b is less than 15.
Combining Logical Operators in Python 3:
We can combine multiple logical operators in Python 3 to create more complex conditions. The order of operations in Python 3 is as follows: NOT, AND, OR.
Example:
a = 10
b = 20
c = 30
if not (a > 5 and b < 5) or c == 20:
print("At least one condition is True.")
else:
print("All conditions are False.")
The output of the above code will be “At least one condition is True.” because the second condition is true.
Conclusion
Logical operators in Python 3 are a powerful way to evaluate conditions and perform actions based on those conditions. With the ability to combine multiple conditions, we can create complex conditions to suit our needs. Remember the order of operations (NOT, AND, OR) when combining these operators. Understanding logical operators is essential to Python 3 programming, and this article provides a foundation to build on. Happy coding!