Exercise 5-11 Solution Python Crash Course Chapter 5: if Statements

 

📘 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:

  1. 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].

  2. Iterate through the list:

    A for loop is used to iterate through each number in the nums list. The variable number takes on each value in the list, one at a time.

  3. 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.
  4. 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:


🔗 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

Previous Post Next Post

Contact Form