Python
Programming Exercises, Gently Explained
100
stringNum = stringNum[1:]
# Remove the negative sign.
else:
isNegative = False
# integerNum holds the converted integer, and starts off at 0:
integerNum = 0
# Loop over the digits in the string from left to right:
for i in range(len(stringNum)):
# Get the integer digit from the string digit:
digit = DIGITS_STR_TO_INT[stringNum[i]]
# Add this to the integer number:
integerNum = (integerNum * 10) + digit
# If the number was originally negative, make the integer
# negative before returning it:
if isNegative:
return -integerNum
else:
return integerNum
The complete solution for this exercise is given in Appendix A and
https://invpy.com/convertstrtoint.py. You can view each step of this program as it
runs under a debugger
at
https://invpy.com/convertstrtoint-debug/.