我不明白为什么“a”+6=24

2024-04-26 02:33:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个正在学习计算机科学的学生,我们正在学习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 a TypeError 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))    

Tags: oftheaddreturnisfunctionlistvalues
1条回答
网友
1楼 · 发布于 2024-04-26 02:33:11

当您catch中的TypeError时,将两个转换为字符串的索引连接起来,除了:

return str(p1) + str(p2)

p1是2,p2是4所以str(2) + str(4)返回字符串24

如果要返回错误:

except TypeError as e:
    return e   

如果您想提高,您需要使用raisenot return

try/except的整个思想是捕获TypeError,而不是引发一个异常,这正是正在发生的事情,尝试将字符串"a"添加到int 6会导致一个TypeError,您捕获并返回两个转换为str并连接的索引。你知道吗

相关问题 更多 >