Python日历控制台项目执行触发NameError,如何修复?
解决你的Python日历程序报错问题
嘿,作为刚接触Python几周的新手,能写出这样的代码已经很棒啦!咱们来一步步搞定这个报错:
第一个错误:变量名不匹配
你定义的事件列表叫termine,但代码最后一行写的是print(events[int(esindices)])——这里的events根本没定义过,Python找不到这个变量,所以抛出了NameError。咱们得把events改成termine才行。
第二个错误:列表转整数的问题
esindices = [i for i, x in enumerate(calendar) if x == date]这行得到的是一个列表(比如输入01.02.2019时会得到[0]),你直接用int(esindices)试图把列表转成整数,Python是不允许的。因为咱们的日历里每个日期应该是唯一的,所以直接取列表的第一个元素就好,也就是esindices[0]。
修改后的完整代码
calendar = ['01.02.2019', '02.02.2019'] termine = ['15:20 playing football', '17:30 playing basketball'] date = str(input('Date: ')) if date in calendar: print('found') # 因为日期唯一,直接用index方法找索引更简单 idx = calendar.index(date) print(f"索引位置:{idx}") print(f"当天事件:{termine[idx]}")
额外小建议:用字典让代码更直观
对于这种“日期-事件”一一对应的场景,Python的字典(dict)会更适合,不用手动处理索引,代码可读性更高,比如:
calendar_dict = { '01.02.2019': '15:20 playing football', '02.02.2019': '17:30 playing basketball' } date = input('Date: ') if date in calendar_dict: print(f"当天事件:{calendar_dict[date]}") else: print("这个日期没有事件哦")
这样是不是更简洁?以后添加事件也更方便~
内容的提问来源于stack exchange,提问作者Felix
相关产品推荐
相关产品推荐

