在读取行时需要帮助解决 EOFerror

Need help resolving EOFerror when reading a line

提问人:TillPickle 提问时间:4/17/2023 最后编辑:BarmarTillPickle 更新时间:4/17/2023 访问量:40

问:

我的代码适用于 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

任何帮助将不胜感激。

Python 错误处理 EOF

评论


答:

0赞 Barmar 4/17/2023 #1

您的脚本需要 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()