我的代码适用于 zybooks 向我抛出的每个输入,但它会在此输入上吐出一个 EOFerror:
2022-01-01
2022-01-01
2022-01-01
2022-01-01
到目前为止,这是我的代码:
from datetime import date, timedelta, time
# 1 Complete read_date()
from datetime import datetime
def read_date():
date_string = input()
return datetime.strptime(date_string, '%Y-%m-%d')
"""Read a string representing a date in the format 2121-04-12, create a
date object from the input string, and return the date object"""
# 2. Use read_date() to read four (unique) date objects, putting the date objects in a list
date_list = []
for i in range(4):
date = read_date()
while date in date_list:
date = read_date()
date_list.append(date)
# 3. Use sorted() to sort the dates, earliest first
sorted_dates = sorted(date_list)
# 4. Output the sorted_dates in order, earliest first, in the format mm/dd/yy
for date in sorted_dates:
print(date.strftime('%m/%d/%Y'))
# 5. Output the number of days between the last two dates in the sorted list
# as a positive number
lastdate = sorted_dates[-1]
secondlastdate = sorted_dates[-2]
daysdifference = (lastdate - secondlastdate).days
print(daysdifference)
# 6. Output the date that is 3 weeks from the most recent date in the list
three_weeks = lastdate + timedelta(weeks = 3)
print(three_weeks.strftime('%B %d, %Y'))
# 7. Output the full name of the day of the week of the earliest day
earliest_day = sorted_dates[0]
print(earliest_day.strftime('%A'))
这是错误:
Traceback (most recent call last):
File "main.py", line 18, in <module>
date = read_date()
File "main.py", line 7, in read_date
date_string = input()
EOFError: EOF when reading a line
任何帮助将不胜感激。
您的脚本需要 4 个不同的日期。此代码:
while date in date_list:
date = read_date()
如果输入重复则要求更换日期。
由于你有 4 个相同的日期,它会停留在这个循环中,最终在到达输入末尾而没有找到不同的日期时出错。
您可以使用
try/except
捕捉这个错误并退出脚本。
try:
for i in range(4):
date = read_date()
while date in date_list:
date = read_date()
date_list.append(date)
except EOFError:
print("Not enough unique dates found, exiting.")
sys.exit()