PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Easy
Question 31
Q181 - Control Flow
What is the expected output of the following code?
- plane = "Cessna"
- counter = 0
- for c in plane * 2:
- if c in ["e", "a"]:
- counter += 1
- print(counter)
-
A
4 -
B
0 -
C
The code is erroneous and cannot be run.
-
D
2
Reveal correct answer
Correct answer: A
Explanation
Topics: for with strings in operator list
add and assign operator
Try it yourself:
- plane = "Cessna"
- counter = 0
- for c in plane * 2:
- if c in ["e", "a"]:
- counter += 1
- print(counter) # 4
Explanation:
plane * 2 evaluates to CessnaCessna
There are two e and two a
and therefore the counter will be 4
Q181 (Please refer to this number, if you want to write me about this question.)
A. The code iterates over the string "CessnaCessna" character by character. It checks if each character is either "e" or "a" and increments the counter if it is. Since there are two "e" and two "a" characters in the string, the final counter value will be 4.
B. The code successfully runs a loop over the string "CessnaCessna" and checks each character if it is either "e" or "a". Since there are two occurrences of "e" and two occurrences of "a" in the string, the counter will be incremented four times, resulting in a final output of 4.
C. The code is not erroneous and can be run successfully. It iterates over the string "CessnaCessna" and counts the occurrences of "e" and "a" characters, resulting in a final output of 4.
D. The code correctly counts the occurrences of "e" and "a" characters in the string "CessnaCessna". Since there are two "e" characters and two "a" characters, the counter will be increased by 2 for each occurrence, resulting in a final output of 4.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
