使用字典和函数的 Python 代码

标签 python python-2.7

我正在尝试使用字典和函数编写一个简单的 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/

相关文章:

python - 如何获取xarray中最大值的坐标?

python - 无法在 python 模块中使用斯坦福 NER

python多处理卡住

Python数据库连接和结果集转换为字符串

python - 在 Python 脚本中检查交互式 shell

python - Wireshark 命令 - python

Python 重命名目录中的多个文件

string - 从字符串列表中查找公共(public)子字符串

Python:从交通摄像头获取 10 分钟视频

android - 如何在python中使用appium按坐标点击