我正在尝试使用字典和函数编写一个简单的 python 代码,如下所示
#Write a program to input number of week's day (1-7) and translate to its equivalent name of the day of the week.
options = { "1" : "sunday",
"2" : "monday",
"3" : "tuesday",
"4" : "wednesday",
"5" : "thursday",
"6" : "friday",
"7" : "saturday" }
options[raw_input("Enter number of weeks day (1-7):")]
def sunday():
print "The day is Sunday"
def monday():
print "The day is Monday"
def tuesday():
print "The day is Tuesday"
def wednesday():
print "The day is Wednesday"
def thursday():
print "The day is Thursday"
def friday():
print "The day is Friday"
def saturday():
print "The day is Saturday"
输出是
[anishjp@localhost Python_programs]$ python hello24.py
Enter number of weeks day (1-7):1
[anishjp@localhost Python_programs]$
它不会打印“今天是星期天”。谁能告诉我,我在这里做错了什么?
最佳答案
字典 options
的键是字符串。您可以改为存储 functions
:
options = { "1" : sunday,
"2" : monday,
"3" : tuesday,
"4" : wednesday,
"5" : thursday,
"6" : friday,
"7" : saturday}
但是,由于您要引用这些函数,因此必须在字典定义之前声明它们:
def sunday():
print "The day is Sunday"
...
def saturday():
print "The day is Saturday"
options = { "1" : sunday,
"2" : monday,
"3" : tuesday,
"4" : wednesday,
"5" : thursday,
"6" : friday,
"7" : saturday}
最后,要调用它,您必须传递参数。您的函数不需要任何参数,因此括号将为空 ()
:
options[raw_input("Enter number of weeks day (1-7):")]()
关于使用字典和函数的 Python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22581207/