Explore the behavior of Python’s reversed() function with strings and integer conversion in this PCAP-31-03 exam question. Learn how to analyze code output for certification success.
Table of Contents
Question
What is the expected behavior of the following code?
string = '123' dummy = 0 for character in reversed(string): dummy += int(character) print(dummy)
A. it outputs 123
B. it raises an exception
C. it outputs 6
D. it outputs 321
Answer
C. it outputs 6
Explanation
Let’s break down the code and explain why:
- string = ‘123’: This creates a string variable containing ‘123’.
- dummy = 0: Initializes a variable ‘dummy’ to 0, which will be used to accumulate our sum.
- for character in reversed(string): This loop iterates over the characters of the string in reverse order. The reversed() function returns an iterator that yields the characters from the string in reverse order.
- dummy += int(character): Inside the loop, each character is converted to an integer using int(), and then added to the ‘dummy’ variable.
- print(dummy): After the loop, the final value of ‘dummy’ is printed.
Here’s how the loop executes:
- First iteration: character = ‘3’, dummy becomes 0 + 3 = 3
- Second iteration: character = ‘2’, dummy becomes 3 + 2 = 5
- Third iteration: character = ‘1’, dummy becomes 5 + 1 = 6
After the loop, dummy contains 6, which is then printed.
This question tests understanding of string manipulation, the reversed() function, type conversion (string to integer), and basic loop operations, all of which are important concepts in the PCAP-31-03 certification exam.
Python Institute PCAP-31-03 certification exam practice question and answer (Q&A) dump with detail explanation and reference available free, helpful to pass the Python Institute PCAP-31-03 exam and earn Python Institute PCAP-31-03 certification.