PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Hard
Question 43
Q468 - Functions
How many plus signs will be printed?
- def fun(n):
- s = '+'
- for i in range(n):
- s += s
- yield s
- for x in fun(2):
- print(x, end='')
-
A
4
-
B
3
-
C
2
-
D
6
Reveal correct answer
Correct answer: D
Explanation
Topics: def for range() yield
Try it yourself:
- def fun(n):
- s = '+'
- for i in range(n):
- s += s
- yield s
- for x in fun(2):
- print(x)
- """
- ++
- ++++
- """
- def fun(n):
- s = '+'
- for i in range(n):
- s += s
- return s
- for x in fun(2):
- print(x)
- """
- +
- +
- """
Explanation:
The generator function fun() will return two plus signs
in the first iteration and four in the second iteration.
yield does not end the function (like return does).
It continues at the same place in the second iteration
and s does not get set back to one plus sign.
At the beginning of the second iteration
s is still two plus signs and becomes four plus signs.
You do the same with return instead of yield
and you would get only two plus signs.
(There is a similar question Q569.)
Q468 (Please refer to this number, if you want to write me about this question.)
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
