Control Flow

Interview Questions for Python Logical Operators

Logical operators in Python are used to perform logical operations on the values of variables. The most commonly used logical operators are and, or, and not. Below are some sample interview questions along with answers about Python logical operators.

Question 1: What are the basic logical operators in Python?

Answer:
The basic logical operators in Python are and, or, and not.

  • and: Returns True if both operands are true
  • or: Returns True if at least one operand is true
  • not: Returns True if the operand is false, and False if it is true

Question 2: How does the and operator work in Python?

Answer:
The and operator evaluates two expressions and returns True only if both expressions are true. If one or both of the expressions evaluate to False, then the and operator returns False.

Example:

Python
print(True and True)  # Output: True
print(True and False) # Output: False
print(False and True) # Output: False
print(False and False) # Output: False

Question 3: How does the or operator work in Python?

Answer:
The or operator evaluates two expressions and returns True if at least one of the expressions is true. If both expressions are false, then it returns False.

Example:

Python
print(True or True)   # Output: True
print(True or False)  # Output: True
print(False or True)  # Output: True
print(False or False) # Output: False

Question 4: How does the not operator work in Python?

Answer:
The not operator reverses the logical state of its operand. If the operand is True, it becomes False, and if it is False, it becomes True.

Example:

Python
print(not True)  # Output: False
print(not False) # Output: True

Question 5: Can you chain logical operators? Provide an example.

Answer:
Yes, you can chain logical operators to create more complex conditions.

Example:

Python
x = 5
y = 10
z = 15

result = x < y and y < z
print(result)  # Output: True

In this example, both x < y and y < z have to be True for result to be True.