📘 Python Crash Course – Chapter 5: if Statements – Exercise 5-11 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
📝 Exercise 5-11
Task:
Ordinal numbers indicate their position in a list, such
as 1st or 2nd . Most ordinal numbers end in th, except 1, 2, and 3 .
• Store the numbers 1 through 9 in a list .
• Loop through the list .
• Use an if-elif-else chain inside the loop to print the proper ordinal end
ing for each number .
Your output should read "1st 2nd 3rd 4th 5th 6th
7th 8th 9th", and each result should be on a separate line
✅ Solution Code:
nums = [1,2,3,4,5,6,7,8,9]
for number in nums :
if number == 1:
print(f'{number}st')
elif number == 2:
print(f'{number}nd')
elif number == 3:
print(f'{number}rd')
else:
print(f'{number}th')
🧠 Code Explanation:
This Python code demonstrates how to use an if-elif-else
chain to determine and display the proper ordinal suffix for numbers. Here's how it works:
-
Create a list of numbers:
The variable
nums
is assigned a list containing the numbers 1 through 9:[1, 2, 3, 4, 5, 6, 7, 8, 9]
. -
Iterate through the list:
A
for
loop is used to iterate through each number in thenums
list. The variablenumber
takes on each value in the list, one at a time. -
Determine the ordinal suffix:
An
if-elif-else
chain is used to determine the appropriate ordinal suffix for each number:if number == 1
: Adds the suffix"st"
for the number 1.elif number == 2
: Adds the suffix"nd"
for the number 2.elif number == 3
: Adds the suffix"rd"
for the number 3.else
: Adds the suffix"th"
for all other numbers.
-
Display the result:
The program outputs each number along with its proper ordinal suffix on a separate line.
This code demonstrates how to use conditional logic to handle special cases and apply specific formatting to a sequence of numbers.
🔍 Output:
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
📚 Related Exercises from Chapter 5:
- ➤ Exercise 5-1 | Conditional Tests
- ➤ Exercise 5-2 | More Conditional Tests
- ➤ Exercise 5-3 | Alien Colors #1
- ➤ Exercise 5-4 | Alien Colors #2
- ➤ Exercise 5-5 | Alien Colors #3
- ➤ Exercise 5-6 | Stages of Life
- ➤ Exercise 5-7 | Favorite Fruit
- ➤ Exercise 5-8 | Hello Admin
- ➤ Exercise 5-9 | No Users
- ➤ Exercise 5-10 | Checking Usernames|
- ➤ Exercise 5-11 | Ordinal Numbers
- ➤ Exercise 5-12 | Styling if statements
- ➤ Exercise 5-13 | Your Ideas
🔗 Connect With Us:
“Programs must be written for people to read, and only incidentally for machines to execute.”
— Harold Abelson
📌 Tags: #Python #PythonCrashCourse #CodingForBeginners #LearnPython #PythonProjects #PythonTips