'Looping through a list in Python
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.")
Solution 1:[1]
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.
Solution 2:[2]
When you say:
if '1' in numbers:
You are checking if that item is in the list, which will be true for every single iteration, so every iteration is going to print '1st'.
What you need to do is check the individual value, which you've specified as numbers but should change to number for each iteration
for number in numbers:
if number == '1': print('{}st.'.format(number))
Hope that makes sense!
Also I just noticed, print(" + number +" "st.")
I'm assuming you're attempting to concatenate strings here. I'd suggest using format, as I've shown above. However to concatenate this statement you'd want to say print(number + "st.")
Solution 3:[3]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
if number == 1:
print(str(number) + "st.")
elif number == 2:
print(str(number)+ "nd.")
elif number == 3:
print(str(number)+ "rd.")
else:
print(str(number)+ "th.")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pastaleg |
Solution 2 | Robbie Milejczak |
Solution 3 | RiveN |