Python 如何简化程序?
我正在尝试用Python3创建一个可以正确输出日历日期的程序。有许多输入,包括月、日和年。根据这些输入,输出应为月/日/年,例如1876年1月26日。但是,我必须注意的一点是每月的最大天数,例如31天,而有些月份为30天。我成功地创建了一个程序,允许某些月份在1月、3月、5月等超过30天。。然而,我的代码效率很低。我使用了一个名为月的列表来存储每个月,并用括号确定了每个月的最大天数。我将使用if语句来显示月份[month-1]==月份[0]一月还是月份[2]三月。然而,程序将其解读为等于一月或三月,这在任何情况下都是如此。这是我发现的生成代码的最有效的方法,但它不起作用。这是我的密码:Python 如何简化程序?,python,date,simplify,Python,Date,Simplify,我正在尝试用Python3创建一个可以正确输出日历日期的程序。有许多输入,包括月、日和年。根据这些输入,输出应为月/日/年,例如1876年1月26日。但是,我必须注意的一点是每月的最大天数,例如31天,而有些月份为30天。我成功地创建了一个程序,允许某些月份在1月、3月、5月等超过30天。。然而,我的代码效率很低。我使用了一个名为月的列表来存储每个月,并用括号确定了每个月的最大天数。我将使用if语句来显示月份[month-1]==月份[0]一月还是月份[2]三月。然而,程序将其解读为等于一月或三
# calendar.py
month = int(input("Put in the month: "))
day = int(input("Put in the day: "))
year = int(input("Put in the year: "))
months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]
# Source of inefficiency (along others)
if months[month - 1] == months[0] or months[month - 1] == months[2] or months[month - 1] == months[4] or months[month - 1] == months[6] or months[month - 1] == months[7] or months[month - 1] == months[9] or months[month - 1] == months[11]:
if day > 31:
print("Invalid date")
else:
months[month - 1] = str(months[month - 1])
day = str(day)
year = str(year)
print(months[month - 1] + "/" + day + "/" + year)
else:
if day > 30:
print("Invalid date")
else:
months[month - 1] = str(months[month - 1])
day = str(day)
year = str(year)
print(months[month - 1] + "/" + day + "/" + year)
最简单的方法是列出月份长度,例如:
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if day > days_in_month[month-1]:
print('Invalid date', file=sys.stderr)
# ... exit, e.g. sys.exit(1)
显然,您仍然需要特殊的逻辑来处理闰年。您可以让标准库进行检查
只需调用datetime.dateyear,month,day如果没有这样的日期,将引发ValueError。闰年处理包括在内
>>> import datetime as dt
>>> dt.date(2019,2,29)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: day is out of range for month
>>> dt.date(2020,2,29)
datetime.date(2020, 2, 29)