PCEP-30-02 · Question #89
What is the expected output of the following code? ``python res = str(bool(1) + float(12) / float(2)) print(res) ``
The correct answer is D. 7.0. D is correct because Python evaluates the expression in operator-precedence order: float(12) / float(2) yields 6.0 (float division), then bool(1) evaluates to True, which - since bool is a subclass of int in Python - acts as 1 in arithmetic. 1 + 6.0 produces 7.0 (int + float…
Question
res = str(bool(1) + float(12) / float(2))
print(res)
Options
- A7
- BThe code is erroneous.
- C6.0
- D7.0
- E6
How the community answered
(62 responses)- A6% (4)
- B2% (1)
- C3% (2)
- D74% (46)
- E15% (9)
Explanation
D is correct because Python evaluates the expression in operator-precedence order: float(12) / float(2) yields 6.0 (float division), then bool(1) evaluates to True, which - since bool is a subclass of int in Python - acts as 1 in arithmetic. 1 + 6.0 produces 7.0 (int + float promotes to float), and str(7.0) gives '7.0', which print outputs as 7.0.
Why the distractors fail:
- A (7) and E (6): Both are integers - impossible here because dividing two floats always returns a float, keeping the result as
7.0or6.0, never a bare int. - C (6.0): Forgets to add
bool(1). It correctly handles the float division but ignores thatTruecontributes1to the sum. - B (erroneous): The code is perfectly valid Python -
bool,float, andstrconversions chain together without error.
Memory tip: Remember "bool is an int in disguise" - True == 1 and False == 0 in any arithmetic context. Also anchor the rule: int + float = float, so once a float enters an expression, the result stays a float.
Community Discussion
No community discussion yet for this question.