Learn Python Daily 25052024.pdf · version 1
Learn Python Daily 25052024.pdf · version 1
Q: How does Python evaluate chained comparisons such as a < b < c? Provide an
example to illustrate potential pitfalls.
A: In Python, chained comparisons like a < b < c are evaluated as a < b and b < c. This
means both conditions must be true for the entire expression to be true.
Example:
python
Copy code
a = 3
b = 5
c = 7
# Potential Pitfall:
a = 3
b = 5
c = 4
A: The == operator checks for value equality, while the is operator checks for identity (i.e.,
whether both operands refer to the same object in memory).
Example:
python
Copy code
a = [1, 2, 3]
b = [1, 2, 3]
# Value equality
print(a == b) # Output: True
# Identity check
print(a is b) # Output: False
# Although a and b have the same values, they are different objects in
memory.
Q: How can you implement custom comparison logic in a class? Provide an example
where you compare two instances of a class using <.
A: You can implement custom comparison logic in a class by defining special methods such
as __lt__ for less-than comparison.
Example:
python
Copy code
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Q: What is the result of comparing a NaN (Not a Number) value with another number
using comparison operators? Why?
A: In Python, comparing a NaN value with any number (including another NaN) using any
comparison operator always results in False. This is because NaN is defined to be
incomparable.
Example:
python
Copy code
import math
nan_value = float('nan')
number = 5
print(nan_value < number) # Output: False
print(nan_value > number) # Output: False
print(nan_value == number) # Output: False
print(nan_value == nan_value) # Output: False
A: Python compares strings lexicographically using the Unicode values of their characters.
Example:
python
Copy code
str1 = "apple"
str2 = "banana"
# Non-intuitive example:
str3 = "apple"
str4 = "Apple"
print(str3 < str4) # Output: False, because lowercase 'a' (97) has a
higher Unicode value than uppercase 'A' (65)