Special Cases and Gotchas
Ensure that the number ends with 11, 12, or 13 before checking if it ends with 1, 2, or 3.
Otherwise, you may end up programming your function to return '213rd' instead of '213th'.
Also, notice that '0' has an ordinal suffix of ―th‖: '0th'.
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/ordinalsuffix-
template.py and paste it into your code editor. Replace the underscores with code to make a working
program:
def ordinalSuffix(number):
numberStr = str(number)
# 11, 12, and 13 have the suffix th:
if numberStr[____:] in ('11', ____, ____):
return numberStr + 'th'
# Numbers that end with 1 have the suffix st:
if numberStr[____] == '1':
return numberStr + 'st'
# Numbers that end with 2 have the suffix nd:
if numberStr[____] == ____:
return numberStr + 'nd'
# Numbers that end with 3 have the suffix rd:
if numberStr[____] == ____:
return numberStr + 'rd'
# All other numbers end with th:
return ____ + ____
The complete solution for this exercise is given in Appendix A and
https://invpy.com/ordinalsuffix.py. You can view each step of this program as it runs under a debugger at
https://invpy.com/ordinalsuffix-debug/.
Another Solution Design
Instead of using the str() function to convert the number to a string and examining the digits
at the end, you could leave it as an integer and determine the last digit with the % modulo operator.
Python Programming Exercises, Gently Explained
22
Any number modulo 10 evaluates to the digit in the one’s place of the number. You can use
modulo 100 to get the last two digits. For example, enter the following into the interactive shell:
>>> 42 % 10
2
>>> 12345 % 10
5
>>> 12345 % 100
45
Using this information, write an alternative solution for this exercise using modulo. If you need
additional hints, replace the underscores in the following solution template with code:
def ordinalSuffix(number):
# 11, 12, and 13 have the suffix th:
if ____ % 100 in (11, ____, ____):
return str(number) + 'th'
# Numbers that end with 1 have the suffix st:
if ____ % 10 == ____:
return str(number) + 'st'
# Numbers that end with 2 have the suffix nd:
if ____ % 10 == ____:
return str(number) + 'nd'
# Numbers that end with 3 have the suffix rd:
if ____ % 10 == ____:
return str(number) + 'rd'
# All other numbers end with th:
return ____(____) + ____
The complete solution for this exercise is given in Appendix A and
https://invpy.com/ordinalsuffix2.py. You can view each step of this program as it runs under a debugger
at https://invpy.com/ordinalsuffix2-debug/.
|