如果
monthStr = months[month-1]
有索引错误,这意味着 month 小于1或大于12.您可以在此行之前检查它是否在正确的范围内 .
几点说明
eval 很危险,在这种情况下不需要 . 您可以使用 split , map 和 int 来提取整数 .
你可以使用 format 和 %02d 来显示日期,如果你想自己写的话
strftime and strptime完全按照自己的意愿行事 . 它们将字符串解析为日期时间并以任何给定格式显示 datetime .
calendar已经month_name . 该列表有13个元素,第一个是空的 .
修改后的代码:
def main():
# get the day month and year
day, month, year = map(int, input("Please enter day, month, year numbers: ").split(','))
date1 = '%02d/%02d/%d' % (day, month, year)
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
if month > 0 and month < 13:
month_str = months[month-1]
## alternative :
# import calendar
# month_str = calendar.month_name[month]
date2 = '%s %d, %d' % (month_str, day, year)
print("The date is", date1, "or", date2+ ".")
else:
print("Invalid month")
main()
举个例子 :
Please enter day, month, year numbers: 24,12,
The date is 24/12/ or December 24, .
但是:
Please enter day, month, year numbers: 24,0,
Invalid month