Special Cases and Gotchas
Several bugs that can occur in our code. We should consider them ahead of writing our code so
we can ensure they don’t sneak past us. These bugs could include:
A comma at the end of number, e.g., 386 producing '386,'
A comma at the front of a number, e.g., 499000 producing ',499,000'
Commas appearing in the fraction part, e.g., 12.3333 producing '12.3,333'
Grouping triplets in reverse order, e.g., 4096 producing '409,6'
However you tackle this exercise, ensure that your code doesn’t make any of these mistakes.
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.
Python Programming Exercises, Gently Explained
103
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/commaformat-
template.py and paste it into your code editor. Replace the underscores with code to make a working
program:
def commaFormat(number):
# Convert the number to a string:
number = str(____)
# Remember the fractional part and remove it from the number, if any:
if '.' in ____:
fractionalPart = number[number.index(____):]
number = number[:number.index('.')]
else:
fractionalPart = ''
# Create a variable to hold triplets of digits and the
# comma-formatted string as it is built:
triplet = ____
commaNumber = ____
# Loop over the digits starting on the right side and going left:
for i in range(len(number) - 1, ____, ____):
# Add the digits to the triplet variable:
triplet = ____[i] + ____
# When the triplet variable has three digits, add it with a
# comma to the comma-formatted string:
if ____(triplet) == ____:
commaNumber = triplet + ',' + ____
# Reset the triplet variable back to a blank string:
triplet = ____
# If the triplet has any digits left over, add it with a comma
# to the comma-formatted string:
if triplet != '':
commaNumber = ____ + ',' + ____
# Return the comma-formatted string:
return ____[:____] + fractionalPart
The complete solution for this exercise is given in Appendix A and
https://invpy.com/commaformat.py. You can view each step of this program as it runs under a debugger at
https://invpy.com/commaformat-debug/.
|