You are on the right track. You can create a dictionary to store the Chinese Zodiac Signs. Since there are 12 of them and to make the math easier, let's get the modulus value of 12 for each year. That makes mod 0 = Monkey,... mod 11 = Goat.
With that, you can do year % 12 will result with a number that we can use to extract the value from the dictionary d
. The way to extract the value from the dictionary is dict[key]
. In our case it will be d[0]
will give Monkey
.
With that, we can write the program as follows:
#define the dictionary with keys. Numbers 0 thru 11 as keys and Zodiac sign as values
d={0:'Monkey',1:'Rooster',2:'Dog',3:'Pig',4:'Rat',5:'Ox',
6:'Tiger',7:'Rabbit',8:'Dragon',9:'Snake',10:'Horse',11:'Goat'}
#define a function that receives the birth year, then returns the Zodiac sign
#as explained earlier we do dict[key]
#year%12 will give the key to use
def chinese_yr(cy):
return d[cy%12]
#get an input from the user. To ensure the value is an int,
#use the statement within a try except statement
while True:
try:
yr = int(input ('enter year :'))
break
except:
print ('Invalid entry. Please enter year')
#call the function with the year as argument
print (chinese_yr(int(yr)))
The output of this will be:
enter year :2011
Rabbit
enter year :2001
Snake
enter year :2020
Rat
enter year :2021
Ox
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…