【问题标题】:date handling issue in Python [duplicate]Python中的日期处理问题[重复]
【发布时间】:2014-03-04 02:48:56
【问题描述】:

我正在做一个处理日期的项目。用户输入月份(以数字形式 - 所以“3”,而不是“3 月”)和年份(2005 年),然后它返回“2005 年 3 月有 31 天。我快完成了,但没有返回月份的名称,它返回数字。所以它说:

3 2005 有 31 天。

这是我的代码:

def enteredMonth():
    month = int(input("Enter a month in terms of a number: "))
    if month == 1:
        month = "January"
    elif month == 2:
        month = "February"
    elif month == 3:
        month = "March"
    elif month == 4:
        month = "April"
    elif month == 5:
        month = "May"
    elif month == 6:
        month = "June"
    elif month == 7:
        month = "July"
    elif month == 8:
        month = "August"
    elif month == 9:
        month = "September"
    elif month == 10:
        month = "October"
    elif month == 11:
        month = "November"
    elif month == 12:
        month = "December"
    return month

def main():
    month = int(input("Enter a month in terms of a number: "))
    year = int(input("Enter a year: "))
    print(month, year, "has", numberOfDays(month, year) , "days")

如何调整代码使其返回月份名称,而不是用户输入的数字?

请帮忙!对此,我真的非常感激。

【问题讨论】:

  • 将结果放在一个单独的变量中,然后返回。 FWIW,字典在这里可能效果更好。
  • 什么意思?可以编辑进去吗?谢谢!
  • @RobertHarvey 有没有办法不使用那种方法来做到这一点?
  • 如果这不是练习:return datetime.date(1970, month, 1).strftime("%B")

标签: python date calendar return


【解决方案1】:

这样的东西有用吗?

def getmonthname:
    months = ['January', 'February', ... , 'December']
    return months[month - 1]

【讨论】:

    【解决方案2】:

    你有你的函数,enteredMonth(),但永远不要在你的代码中使用它。

    print(enteredMonth(month), year, "has", numberOfDays(month, year), "days")
    

    但优化enteredMonth 的更好方法是简单地使用字典:

    months = {
        1: 'January'
        2: 'February'
        ...
    }
    

    然后你可以访问每个月的字符串及其编号,如下所示:

    >>> months[1]
    'January'
    >>> months[4]
    'April'
    

    【讨论】:

    • @akaRem 我将如何使用元组?
    • {1:, 2:, ..} -> (, , ...),所以 .. 索引有效,添加/附加/ pop 不需要,但几个月后你不需要它
    • @akaRem 除了索引从 0 开始,这引发了我在 Oscar 的回答下提出的问题。
    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2014-11-04
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    相关资源
    最近更新 更多