Special Cases and Gotchas
At the start of the function, check if the integerNum parameter is 0 and, if so, immediately
return the string '0'. Our algorithm is such that otherwise it will return the blank string '' for 0,
which is incorrect.
Python Programming Exercises, Gently Explained
97
Now try to write a solution based on the information in the previous sections. If you still have
trouble solving this exercise, read the Solution Template section for additional hints.
Solution Template
Try to first write a solution from scratch. But if you have difficulty, you can use the following
partial program as a starting place. Copy the following code from https://invpy.com/convertinttostr-
template.py and paste it into your code editor. Replace the underscores with code to make a working
program:
def convertIntToStr(integerNum):
# Special case: Check if integerNum is 0, and return '0' if so:
if integerNum == ____:
return ____
# This dictionary maps single integer digits to string digits:
DIGITS_INT_TO_STR = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4',
5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}
# Make a note whether the number is negative or not, and make
# integerNum positive for the rest of the function's code:
if integerNum < ____:
isNegative = ____
integerNum = ____
else:
isNegative = ____
# stringNum holds the converted string, and starts off blank:
stringNum = ____
# Keeping looping while integerNum is greater than zero:
while integerNum ____ 0:
# Mod the integerNum by 10 to get the digit in the ones place:
onesPlaceDigit = integerNum % ____
# Put the corresponding string digit at the front of stringNum:
stringNum = DIGITS_INT_TO_STR[onesPlaceDigit] + ____
# Divide integerNum by ten to remove one entire digit place:
integerNum //= ____
# If the number was originally negative, add a minus sign:
if isNegative:
return ____ + stringNum
else:
return ____
The complete solution for this exercise is given in Appendix A and
https://invpy.com/convertinttostr.py. You can view each step of this program as it runs under a debugger
at https://invpy.com/convertinttostr-debug/.
|