PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Medium
Question 32
Q620 - Functions
What is the expected output of the following code?
- def func(x):
- if x % 2 == 0:
- return 1
- else:
- return 2
- print(func(func(2)))
-
A
0 -
B
The code is erroneous.
-
C
1 -
D
2
Reveal correct answer
Correct answer: D
Explanation
Topics: def if else modulus operator
Try it yourself:
- def func(x):
- if x % 2 == 0:
- return 1
- else:
- return 2
- print(func(func(2))) # 2
Explanation:
The condition x % 2 == 0 tests for even numbers.
The first function call func(2) passes an even number
and the return value will be 2
The second function call will do the same.
(There is a similar question Q520.)
Q620 (Please refer to this number, if you want to write me about this question.)
A. This output is incorrect because the inner function call func(2) will return 1 since 2 is an even number. The outer function call func(1) will then return 2 as it is an odd number.
B. This choice is incorrect as the code is not erroneous. The function func is defined correctly and the code will execute without any errors.
C. This output is incorrect because the inner function call func(2) will return 1 since 2 is an even number. The outer function call func(1) will then return 2 as it is an odd number.
D. The input to the outer function func is 2, which is an even number, so the inner function call func(2) will return 1. Therefore, the outer function call func(1) will return 2 as it is an odd number.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
