处理重复日期输入时触发EOFError问题求助
问题:输入重复日期时抛出EOFError错误
我的代码在zyBooks的常规输入下都能正常运行,但当输入4个完全相同的日期时(如下),会抛出EOFError:
2022-01-01
2022-01-01
2022-01-01
2022-01-01
错误栈信息如下:
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
原代码
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'))
问题原因与修复方案
原因
代码逻辑要求读取4个唯一的日期,但当输入只有4个相同日期时,第一次读取的日期已经在date_list里,进入while循环后会继续调用read_date()尝试获取新输入,但此时已经没有更多输入了,所以触发EOFError。
修复方案
方案1:添加EOF异常处理
修改read_date()函数,捕获EOFError并给出提示后退出,避免程序崩溃:
def read_date(): try: date_string = input() return datetime.strptime(date_string, '%Y-%m-%d') except EOFError: print("错误:输入不足,无法获取足够的唯一日期") exit(1)
方案2:调整输入逻辑,提前处理所有输入
如果是批处理输入场景,先一次性读取所有输入,再筛选唯一日期,从根源避免循环等待输入的问题:
from datetime import date, timedelta, datetime def read_dates_from_input(): import sys # 读取所有非空输入行 lines = [line.strip() for line in sys.stdin if line.strip()] dates = [] for line in lines: try: dates.append(datetime.strptime(line, '%Y-%m-%d')) except ValueError: print(f"无效日期格式:{line}") exit(1) return dates # 获取所有输入日期并提取唯一值 all_dates = read_dates_from_input() unique_dates = list(set(all_dates)) # 检查唯一日期数量是否满足要求 if len(unique_dates) < 4: print("错误:输入的唯一日期数量不足4个") exit(1) # 取前4个唯一日期(若超过4个则截断) date_list = unique_dates[:4] # 后续逻辑保持不变 sorted_dates = sorted(date_list) for date in sorted_dates: print(date.strftime('%m/%d/%Y')) lastdate = sorted_dates[-1] secondlastdate = sorted_dates[-2] daysdifference = (lastdate - secondlastdate).days print(daysdifference) three_weeks = lastdate + timedelta(weeks = 3) print(three_weeks.strftime('%B %d, %Y')) earliest_day = sorted_dates[0] print(earliest_day.strftime('%A'))
内容的提问来源于stack exchange,提问作者TillPickle
相关产品推荐
相关产品推荐

