【发布时间】:2021-04-14 14:42:04
【问题描述】:
当我在函数之前使用 try 时,它会引发错误。但如果我在 in 中使用它,它会很好。为什么?(这些代码的评估顺序是什么?)。任何帮助表示赞赏。
try:
def chiz(dict, key):
return dict[key]
except:
print("somethig went wrong")
user_01 = {
"name": "armin",
"age": 20.51
}
chiz(user_01, "weight")
>>>Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\pythonWhile\test.py", line 11, in <module>
chiz(user_01, "weight")
File "C:\Users\user\PycharmProjects\pythonWhile\test.py", line 3, in chiz
return dict[key]
KeyError: 'weight'
def chiz(dict, key):
try:
return dict[key]
except :
print("somethig went wrong")
user_01 = {
"name": "armin",
"age": 20.51
}
chiz(user_01, "weight")
【问题讨论】:
-
在您的第一个代码中,
try所做的只是 define 一个函数,在您的第二种情况下,您实际上是 execute 该代码 sn-p
标签: python try-except