用于将日期转换为数字的Python程序

时间:2017-03-25 18:11:28

标签: python

我想制作一个需要日,月和年的程序,并以下列格式打印:     2016年3月14日。 我收到这个错误:

  File "date.py", line 23
    else:
       ^
SyntaxError: invalid syntax

我的问题是什么?以及如何修复代码? 这是我的代码:

def get_month_english(month):
    if (month == 1):
        return "January"
    else:
        if (month == 2):
            return "February"
    else:
        if (month == 3):
            return "March"
    else:
        if (month == 4):
            return "April"
    else:
        if (month == 5):
            return "May"
    else:
        if (month == 6):
            return "June"
    else:
        if (month == 7):
            return "July"
    else:
        if (month == 8):
            return "August"
    else:
        if (month == 9):
            return "September"
    else:
        if (month == 10):
            return "October"
    else:
        if (month == 11):
            return "November"
    else:
        return "December"

2 个答案:

答案 0 :(得分:2)

我建议您不要使用一系列条件,而只需使用列表:

def get_month_english(month):
    months = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    ]
    return months[month-1]

或者,也许是字典,所以你不必减去1来获得正确的索引:

def get_month_english(month):
    months = {
        1: "January",
        2: "February",
        3: "March",
        4: "April",
        5: "May",
        6: "June",
        7: "July",
        8: "August",
        9: "September",
        10: "October",
        11: "November",
        12: "December"
    }
    return months[month]

答案 1 :(得分:0)

通过本教程是值得的 -

https://www.tutorialspoint.com/python/python_if_else.htm

完成上述操作后,您应该能够证明以下代码的合理性

def get_month_english(month):
    if (month == 1):
        return "January"
    elif (month == 2):
            return "February"
    elif (month == 3):
            return "March"
    elif (month == 4):
            return "April"
    elif (month == 5):
            return "May"
    elif (month == 6):
            return "June"
    elif (month == 7):
            return "July"
    elif (month == 8):
            return "August"
    elif (month == 9):
            return "September"
    elif (month == 10):
            return "October"
    elif (month == 11):
            return "November"
    else:
        return "December"