作业:提示用户输入他们的出生月份,然后输入他们的出生日期。打印月份名称后跟日期
The assignment: Prompt user to input their Birthmonth then input the day they were born. Print the month's name followed by the day
我试着通过简单地逐月逐月地做这件事很长的路要走,但我的老师告诉我,太长的时间是不可接受的。现在我打印了日期和月份,但不确定如何快速将给定的数字更改为它代表的月份。这是我目前所拥有的。
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)
它会打印数字和日期,这很好,但她不希望我列出所有月份。如果能得到任何帮助,我将不胜感激。
您可以使用 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
模块。
我试着通过简单地逐月逐月地做这件事很长的路要走,但我的老师告诉我,太长的时间是不可接受的。现在我打印了日期和月份,但不确定如何快速将给定的数字更改为它代表的月份。这是我目前所拥有的。
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)
它会打印数字和日期,这很好,但她不希望我列出所有月份。如果能得到任何帮助,我将不胜感激。
您可以使用 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
模块。