Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

for statement from dictionary, python

Basically, I am new to programming and I sign up for a python course. I receive an exercise asking as follow:

Build a function that returns, given an arbitrary birth year, the Chinese zodiac sign corresponding to that calendar year. You start from a dictionary of Chinese zodiac signs from 2001-2012 (covering the whole 12-sign cycle)

So my idea is to create a dictionary,

d={2001:'Snake',2002:'Horse',2003:'Goat',2004:'Monkey',2005:'Rooster',2006:'Dog',
           2007:'Pig',2008:'Rat',2009:'Ox',2010:'Tiger',2011:'Rabbit',2012:'Dragon'}

And I begin with the for statement

def year(x):
    for x in d.keys:
        if x=d.keys:
            print d.value
        else:
        x..

I basically have no idea how to approach the next step. Can someone please me some direction?

question from:https://stackoverflow.com/questions/65838141/for-statement-from-dictionary-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...