Ordinal numbers

Asked

Viewed 295 times

0

Hello, I’m starting programming and I’m studying Python. Performing an exercise I managed to get the expected result. However, when I try to do the same program by converting the list to INT, it doesn’t work. Shows output error, even add a class int in the Print command. Can anyone ask me this question?

lista_numeros = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

for lista in lista_numeros:
    if lista == '1':
        print(lista + 'st')

    elif lista == '2':
        print(lista + 'nd')

    elif lista == '3':
        print(lista + 'rd')

    else:
        print(lista + 'th')
  • What would be the problematic code? That?

  • I just tested your code and there was no error.

1 answer

3


If you turn the list to int will need to convert the linha for string before concatenating and printing. Also change the comparison values in commands if. The conclusion is that you can convert, it just doesn’t make sense because the code will get more confused. It follows how it would look:

lista_numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for lista in lista_numeros:

    if lista == 1:
        print(str(lista) + 'st')

    elif lista == 2:
        print(str(lista) + 'nd')

    elif lista == 3:
        print(str(lista) + 'rd')

    else:
        print(str(lista) + 'th')
  • I was doing it in a totally different way, thanks for the help.

  • 1

    The line str(lista).split(',') does not make sense and does not need to be in the code. OP problem is solved with variable conversion lista for str at the time of print.

  • 1

    Gratefully Gabriel, I edited my reply as per your comment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.