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
: ReturnsTrue
if both operands are trueor
: ReturnsTrue
if at least one operand is truenot
: ReturnsTrue
if the operand is false, andFalse
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:
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:
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:
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:
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
.