基本上,我是编程新手,我报名参加了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..
我基本上不知道如何进行下一步。有人能告诉我一些方向吗
首先,感谢Jakob和Steve,我从未想过使用模数。所以我调整了字典和密码
有趣的是,我的代码只能返回“龙”
你在正确的轨道上。您可以创建一本字典来存储中国的生肖。因为有12个,为了简化数学计算,让我们每年得到12的模数值。这使得mod 0=Monkey,。。。mod 11=山羊
这样,您就可以执行第%12年的操作,结果将是一个数字,我们可以使用该数字从字典
d
中提取值。从字典中提取值的方法是dict[key]
。在我们的例子中d[0]
将给出Monkey
这样,我们就可以编写如下程序:
其输出将为:
相关问题 更多 >
编程相关推荐