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/.