PCEP-30-02 · Question #177
What is the expected output of the following code? ``python def func1(x): return str(x) def func2(x): return str(2 * x) print(func1(1) + func2(2)) ``
The correct answer is D. 14. D is correct because both functions return strings via str(), so the + operator performs string concatenation, not addition. func1(1) returns "1" and func2(2) returns str(2 2) = "4", giving "1" + "4" = "14". Why the distractors fail: A (3) assumes numeric addition of the inputs…
Question
def func1(x):
return str(x)
def func2(x):
return str(2 * x)
print(func1(1) + func2(2))
Options
- A3
- B5
- CThe code is erroneous.
- D14
How the community answered
(25 responses)- A12% (3)
- B4% (1)
- C4% (1)
- D80% (20)
Explanation
D is correct because both functions return strings via str(), so the + operator performs string concatenation, not addition. func1(1) returns "1" and func2(2) returns str(2 * 2) = "4", giving "1" + "4" = "14".
Why the distractors fail:
- A (3) assumes numeric addition of the inputs (1 + 2), ignoring that
func2doubles its argument before converting. - B (5) assumes numeric addition of the computed values (1 + 4), forgetting that
str()makes them strings, not integers. - C is wrong because the code is perfectly valid Python - it runs without error.
Memory tip: Whenever you see str() in a function return, mentally replace + with "glue" instead of "add." Strings glue side-by-side ("1" glued to "4" = "14"), they don't sum numerically.
Community Discussion
No community discussion yet for this question.