Search code examples
pythonpython-3.xloopsfor-loopordinal

Find ordinal numbers with loop dynamically: find th - st - nd - rd


I would like to find dynamically the correct ordinal number root for instance:

111 = 111st
112 = 112nd 
113 = 113rd ...

I tried other solutions but I can't find a good one.

This is my code:

for number in range(1, 114):
    print(number)
    ex1 = 11
    ex2 = 12
    ex3 = 13
    if number == ex1:
        print("is the " + str(number) + "th number.")
    elif number % 10 == 1 or not ex1:
        print("is the " + str(number) + "st number.")
    elif number == ex2:
        print("is the " + str(number) + "nd number.")
    elif number % 10 == 2 or not ex2:
        print("is the " + str(number) + "nd number.")
    elif number == ex3:
        print("is the " + str(number) + "rd number.")
    elif number % 10 == 3 or not ex3:
        print("is the " + str(number) + "rd number")
    else:
        print("is the " + str(number) + "th number.")

Solution

  • So, the problem is that 111 gets displayed as 111st instead of 111th.

    You have 11 as ex1, I assume short for "exception 1", but your condition:

    if number == ex1:
    

    Clearly doesn't match 111.

    Instead you could do:

    if number % 100 == ex1:
    

    Which will be true for 11, 111, 211 etc.

    On a side note:

    elif number % 10 == 1 or not ex1:
    

    Clearly isn't what you intended. This is interpreted as:

    elif (number % 10 == 1) or (not ex1):
    

    not ex1 does not depend on number and will always evaluate the same way (False). But since you're already checking ex1 separately, it would be redundant to do it correctly here.

    If you wanted to correct that, so that you don't need to check ex1 twice, you'd do this:

    if number % 10 == 1 and number % 100 != 11:
    

    I think in this case using != is clearer than not and I don't think there is any benefit from assigning a variable to 11.