【发布时间】:2019-11-28 18:10:02
【问题描述】:
下面,我们提供了一个元组列表,其中包含学生姓名、期末考试成绩以及他们是否会通过课程。对于一些学生来说,元组没有第三个元素,因为不知道他们是否会通过。目前,for 循环不起作用。添加一个 try/except 子句,以便代码运行时不会出错 - 如果元组中没有第三个元素,则不应对字典进行任何更改。
students = [('Timmy', 95, 'Will pass'), ('Martha', 70), ('Betty', 82, 'Will pass'), ('Stewart', 50,
'Will not pass'), ('Ashley', 68), ('Natalie', 99, 'Will pass'), ('Archie', 71), ('Carl',
45, 'Will not pass')]
passing = {'Will pass': 0, 'Will not pass': 0}
for tup in students:
if tup[2] == 'Will pass':
passing['Will pass'] += 1
elif tup[2] == 'Will not pass':
passing['Will not pass'] += 1
如果上面的代码运行,它会给出错误:IndexError: tuple index out of range on line 8 在 try/except 之后,它应该给出 {'Will pass': 3, 'Will not pass':2}
我的尝试是:
try:
for tup in students:
if tup[2] == 'Will pass':
passing['Will pass'] += 1
elif tup[2] == 'Will not pass':
passing['Will not pass'] += 1
except Exception, e:
print("Continue")
它给出{‘会通过’: 1, ‘不会通过’:0}
有人可以告诉我的尝试/例外有什么问题吗?我尝试添加两个 try/except,但仍然得到相同的输出。
【问题讨论】:
-
print("Continue")不继续循环;它打印"Continue"。 -
您可能希望将
try-except带入循环并使用continue。 -
...并且还捕获 IndexError 而不是 Exception 因为您知道这是您要得到的错误