我是一个正在学习计算机科学的学生,我们正在学习try:除了:我在这个问题上碰到了障碍,我就是想不出来。你知道吗
For this exercise you should define a function called
add_list_values()
which is passed a list of values as well as two index positions. The function should return the sum of the two values at the specified index positions.For example, if the list is:
myList = [4,2,6,7,8,1]
then the function call:
add_list_values(myList, 2, 4)
should return the value 14.
A couple of things could go wrong here. Firstly, if a sequence subscript is out of range, then an
IndexError
will be generated. And of course, unless both operands are numeric, then aTypeError
will occur indicating that the the addition could not be completed.Define the
add_list_values()
function, taking into account these possible exceptions. Please note:
- If an
IndexError
occurs, then the function should return 0- If a
TypeError
occurs, then the function should return the string concatenation of the two values
出于某种原因,当我进入第二个列表而不是抛出错误时,我得到了答案(24)?你知道吗
我想知道如何检查字符串列表,以便识别该字符串并调用TypeError
。你知道吗
def add_list_values(myList, p1, p2):
try:
print (myList[p1])
print (myList[p2])
answer = myList[p1] + myList[p2]
return answer
except IndexError:
return 0
except TypeError:
return str(p1)+str(p2)
#myList = [4,2,6,7,-2,100]
#print(add_list_values(myList, 2, 4))
myList = [4,2,6,7,"a",100]
print(add_list_values(myList, 2, 4))
#myList = [4,2,6,7,-6,100]
#print(add_list_values(myList, 2, -400))
当您
catch
中的TypeError
时,将两个转换为字符串的索引连接起来,除了:p1
是2,p2
是4所以str(2) + str(4)
返回字符串24
如果要返回错误:
如果您想提高,您需要使用
raise
not returntry/except的整个思想是捕获
TypeError
,而不是引发一个异常,这正是正在发生的事情,尝试将字符串"a"
添加到int6
会导致一个TypeError,您捕获并返回两个转换为str并连接的索引。你知道吗相关问题 更多 >
编程相关推荐