Trying to loop through a list of numbers so that the output reads the result on a seperate line.
Instructions Given: - Store numbers 1-9 in a list. - Loop through the list. - Using if-elif-else chain inside the loop to print the appropriate ending for each number. The output should read "1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th" with each result on a seperate line. Most ordinal numbers end in "th" except for 1st, 2nd, 3rd.
My Problem: I am having an issue with the individual loop code.
What is the correct way to write this?
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
for numbers in numbers:
if '1' in numbers:
print(" + number +" "st.")
elif '2' in numbers:
print(" + number + " "nd.")
elif '3' in numbers:
print(" + number + " "rd.")
else:
print(" + number +" "th.")
You are close. In your for loop, you want the enumerator to be different than the list you are enumerating. Then that enumerator contains the object you are comparing, so in the print you don't need the quotes around number
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
for number in numbers:
if '1' in number:
print( number +"st.")
elif '2' in number:
print(number + "nd.")
elif '3' in number:
print( number + "rd.")
else:
print(number +"th.")
To answer your last question, there is no one correct way to do it. Different people have different approaches depending on personal preference and level of knowledge of the language.