PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Easy
Question 7
You are developing a custom class MyInt that inherits from the built-in int class in Python. You want to add a new method is_even() that will return True if the integer is even, and False if it's odd. Which of the following methods is the best way to implement is_even()?
-
A
- def is_even(self):
- if self % 2 == 0:
- return True
- else:
- return False
-
B
- def is_even(self):
- return True if self % 2 == 0 else False
-
C
- def is_even(self):
- return not self % 2
-
D
- def is_even(self):
- return self % 2 == 0
Reveal correct answer
Correct answer: D
A.
Although this method would work, it's unnecessarily verbose. The expression self % 2 == 0 already returns a boolean, so there's no need for an if-else structure.
B.
This method is unnecessarily verbose. The expression inside the conditional operator is already a boolean.
C.
This is correct in terms of functionality but might be a bit harder to understand for someone reading the code because it relies on the fact that 0 is considered False in a boolean context. While it's okay to use this kind of "trick" in your code, the method in B is just as efficient and arguably more clear.
D.
The expression self % 2 == 0 returns True if self is even and False if it's odd. This is the most concise and Pythonic way to implement the method.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
