Syntax and Usage
Basic Syntax
Logical operators in Python are straightforward to use:
- and: Returns True if both statements are true.
- or: Returns True if one of the statements is true.
- not: Returns the opposite of the statement.
Operator Precedence
Understanding operator precedence helps in evaluating complex expressions:
- not has the highest precedence, followed by and, and then or.
Examples of Logical Operators
Example 1: Using and Operator
Python
# Example of 'and' operator
a = 10
b = 5
c = 20
if a > b and c > a:
print("Both conditions are true")
else:
print("At least one condition is false")

You can also try this code with Online Python Compiler
Run Code
Output:
Both conditions are true
Example 2: Using or Operator
Python
# Example of 'or' operator
x = 10
y = 5
if x > 5 or y > 10:
print("At least one condition is true")
else:
print("Both conditions are false")

You can also try this code with Online Python Compiler
Run Code
Output
At least one condition is true
Example 3: Using not Operator
Python
# Example of 'not' operator
flag = False
if not flag:
print("Flag is False")
else:
print("Flag is True")

You can also try this code with Online Python Compiler
Run Code
Output
Flag is False
Combining Logical Operators
You can combine multiple logical operators to create more complex conditions:
Python
# Combining logical operators
num = 15
if num > 0 and num % 2 == 0:
print("Number is positive and even")
else:
print("Number is either negative or odd")

You can also try this code with Online Python Compiler
Run Code
Output
Number is either negative or odd
Frequently Asked Questions
What are logical operators in Python?
Python logical operators (and, or, not) are used to combine conditional statements.
How do and, or, and not operators work in Python?
and returns True if both conditions are true. or returns True if at least one condition is true. not returns the opposite boolean value.
What is the precedence of logical operators in Python?
not has the highest precedence, followed by and, and then or.
Conclusion
Python logical operators are fundamental tools for creating flexible and efficient decision-making in programming. By mastering these operators and understanding their nuances, you can write clearer, more concise, and error-free code.