【问题标题】:The assignment: Prompt user to input their Birthmonth then input the day they were born. Print the month's name followed by the day任务:提示用户输入他们的出生月份,然后输入他们出生的日期。打印月份名称,后跟日期
【发布时间】:2017-08-09 01:21:33
【问题描述】:

我尝试通过简单地一个接一个地减少几个月来做到这一点,但我的老师告诉我,长时间是不可接受的。现在我打印了日期和月份,但不知道如何快速将给出的数字更改为它所代表的月份。这是我目前所拥有的。

    birthMonth = int(input("Enter your Birth Month:"))

if birthMonth <= 0 or birthMonth > 12:
   print("Invalid, Choose again")
else:
    birthDay = int(input("What day?:"))
    if birthDay <=0 or birthDay > 31:
        print('Not a valid Birthday')
    else:
        print(birthMonth, birthDay)

它会打印数字和日期,这很好,但她不希望我列出所有月份。如果能得到任何帮助,我将不胜感激。

【问题讨论】:

标签: python loops date names


【解决方案1】:

您可以使用datetime 模块获取与数字关联的月份。

>>> import datetime
>>> month_num = 8
>>> month = datetime.date(2017, month_num, 1).strftime("%B")
>>> print(month)
August

另一种选择(可能更好)是使用calendar 模块

>>> import calendar
>>> month_num = 8
>>> calendar.month_name[month_num]
August

所以,在你的代码中,你可以替换

print(birthMonth, birthDay)

与

print(calendar.month_name[birthMonth], birthDay)

但是,请确保您导入了 calendar 模块。

【讨论】:

  • 非常感谢!谢谢你这么快回答^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多