Bilbo Bilbo - 22 days ago 6
Python Question

Reducing the number of conditionals in a small python script

I have been developing a small program.
It works perfectly how it is but I want to make the code a bit smaller.

import time, math
name= input("Enter Your Name: ")
age= int(input("Enter Your Age: "))
end= "th"
if age == 3 or age == 13 or age == 23 or age == 33 or age == 43 or age == 53 or age == 63 or age == 73 or age == 83 or age == 93:
end= "rd"

if age == 2 or age == 22 or age == 32 or age == 42 or age == 52 or age == 62 or age == 72 or age == 82 or age == 92:
end= "nd"

print ("Your Name Is "+ name + ", You Are " + str(age) + " Years Old.")
print ("Hi " + name + ", Happy " + str(age) + end + " birthday!")
time.sleep(5)


I would like to have an easier way to change the 'end' to other values without having to write them all, can I have it start at 3 then do it for everything 10 more than three.

Answer

Use the modulo operator:

if age % 10 == 3:
    end = "rd"
elif age % 10 == 2:
    end = "nd"

Or use a dict:

ends = {2: "nd", 3: "rd"}
end = ends[age % 10]

You can also use a default:

ends = {1: "st", 2: "nd", 3: "rd"}
end = ends.get(age % 10, "th)