I am writing a program in python that will take user birthday input and output their western and chinese zodiac sign. Right now I am just trying to get the Chinese sign working. This is my code so far:
ZODIAC = [(1900, "Rat"), (1901, "Ox"), (1902, "Tiger"), (1903, "Rabbit"), (1904\
, "Dragon"), (1905, "Snake"), (1906, "Horse"), (1907, "Sheep"), (1908, "Monkey"\
), (1909, "Rooster"), (1910, "Dog"), (1911, "Pig")]
def getChineseZodiac(year):
for i in ZODIAC:
if (year - ZODIAC[i]) % 12 == 0:
return ZODIAC[i]
year = input("Enter a year: ")
getChineseZodiac(year)
What I hope for this code to do is to run through each of those years in ZODIAC and find a match with modulus 0, and then return the string attached. But the error I get is TypeError: list indices must be integers, not tuple. How do I solve this?
Am I supposed to be using some other format for ZODIAC?
The exception you are getting is because of the way you are indexing the list.
for i in ZODIACsetsito a member of ZODIAC, not to an index. You can’t then useZODIAC[i]and have it make sense. Instead, useidirectly (in this case, by usingi[0]andiin place of the two cases where you were usingZODIAC[i]). Or alternatively, if you do want to iterate over indexes, change your loop to usefor i in range(len(ZODIAC)).However, the whole problem can be simplified. Since the signs in your list are in order, you can do just a single modulus calculation and use it as an index into the list, rather than iterating over the list values and testing each one: