Solution Design Despite involving numbers, this exercise is actually about text manipulation. The characters of
the string just happen to be numeric digits.
First, we convert the number argument to a string with the str() function. This will work
whether the number is an integer or a floating-point number. Once we have the number as a string,
we can check for the existence of a period which indicates it was a floating-point number with a
fractional part. The expression '.' in number evaluates to True if the string in number has a
period character. Next, we can use number.index('.') to find the index of this period character.
(The index() method raises a ValueError exception if '.' doesn’t appear in the string, but the
previous '.' in number expression being True guarantees that it does.)
We need to remove this fractional part from number while saving it in another variable to add
back in later. This way we are only adding commas to the whole number part of the number
argument, whether or not it was an integer or floating-point number.
Next, let’s start variables named triplet and commaNumber as blank strings. As we loop over
the digits of number, the triplet variable will store digits until it has three of them, at which point
we add them to commaNumber (which contains the comma-formatted version of number) with a
comma. The first time we add triplet to commaNumber, there will be an extra comma at the end
of a number. For example, the triplet '248' gets added to commaNumber as '248,'. We can
remove the extra comma just before returning the number.
We need to loop starting at the one’s place in the number and moving left, so our for loop
should work in reverse: for i in range(len(number) - 1, -1, -1). For example, if
number
is 4096, then the first iteration of the loop can access number[3], the second iteration can
access number[2], and so on. This way the first triplet ends up being '096' instead of '409'.
If the loop finishes and there are leftover digits in triplet, add them to commaNumber with a
comma. Finally, return commaNumber except with the comma at the end truncated:
commaNumber[:-1]
evaluates to everything in commaNumber except the last character.
Finally, we need to add the fractional part back in the number if there was one originally.