对于字典中的语句,python

2024-09-28 20:47:24 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我是编程新手,我报名参加了python课程。我收到一份练习,要求如下:

构建一个函数,给定任意的出生年份,返回对应于该日历年的中国生肖。从2001-2012年的中国生肖词典开始(涵盖整个12个星座周期)

所以我的想法是编一本字典

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'}

我从for语句开始

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

我基本上不知道如何进行下一步。有人能告诉我一些方向吗


Tags: 函数for字典编程keys课程词典monkey
2条回答

首先,感谢Jakob和Steve,我从未想过使用模数。所以我调整了字典和密码

d={9:'Snake',10:'Horse',11:'Goat',0:'Monkey',1:'Rooster',2:'Dog',
           3:'Pig',4:'Rat',5:'Ox',6:'Tiger',7:'Rabbit',8:'Dragon'}

def get_Chinese_zodiac(x):
for x in d:
    x=x%12
return d[x]

有趣的是,我的代码只能返回“龙”

你在正确的轨道上。您可以创建一本字典来存储中国的生肖。因为有12个,为了简化数学计算,让我们每年得到12的模数值。这使得mod 0=Monkey,。。。mod 11=山羊

这样,您就可以执行第%12年的操作,结果将是一个数字,我们可以使用该数字从字典d中提取值。从字典中提取值的方法是dict[key]。在我们的例子中d[0]将给出Monkey

这样,我们就可以编写如下程序:

#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)))

其输出将为:

enter year :2011
Rabbit

enter year :2001
Snake

enter year :2020
Rat

enter year :2021
Ox

相关问题 更多 >