python-3.xordinals

Ordinal Number Error, Python 3


I have a problem with my Python code. I am trying to display the ordinal number of the users input. So if I typed 32 it would display 32nd, or if I typed 576 it would display 576th. The only thing that doesn't work is 93, it displays 93th. Every other number works and I am not sure why. Here is my code:

num = input ('Enter a number: ')
end = ''
if num[len(num) - 2] != '1' or len(num) == 1:
  if num.endswith('1'):
    end = 'st'
  elif num.endswith('2'):
    end = 'nd'
  elif num == '3':
    end = 'rd'
  else:
    end = 'th'
else:
  end = 'th'
ornum = num + end
print (ornum)

Solution

  • You use endswith() at 2 places, instead of 3:

    if num.endswith('1'):
        end = 'st'
    elif num.endswith('2'):
        end = 'nd'
    #elif num == '3':  WRONG
    elif num.endswith('3'):
        end = 'rd'
    

    In your code, it will test 'if num is equal to 3' instead of 'if num ends with 3'.