gpt4 book ai didi

python - 为什么 Python 不在 try 语句上实现 elif 语句?

转载 作者:太空狗 更新时间:2023-10-29 18:30:25 25 4
gpt4 key购买 nike

让我们举一个简单的例子。

my_list = [
{"name": "toto", "value": 3},
{"name": "foo", "value": 42},
{"name": "bar", "value": 56}
]

def foo(name):
try:
value = next(e["value"] for e in my_list if e["name"] == name)
except StopIteration:
print "Uuuh not found."
else:
if value % 2:
print "Odd !"
else:
print "Even !"

如您所见,上面的代码有效:

>>> foo("toto")
Odd !
>>> foo("foo")
Even !
>>> foo("kappa")
Uuuh not found.

我只是想知道为什么我们不能像这样将 elif 语句与 try 语句一起使用是否有特殊原因:

try:
value = next(e["value"] for e in my_list if e["name"] == name)
except StopIteration:
print "Uuuh not found."
elif value % 2:
print "Odd !"
else:
print "Even !"

当然,这是行不通的,因为它是在 try statement documentation 中定义的, elif 语句未定义。但为什么 ?是否有特殊原因(如绑定(bind)/未绑定(bind)变量)?有这方面的任何资料吗?

(旁注:没有 elif-statement 标签?)

最佳答案

如果你问为什么那么这是 python 开发者的问题,语法在 docs 中明确定义。你链接到。

除此之外,您尝试做的事情显然都可以在 try/except 中完成。如果你使用一个 else 它属于 try 就像你使用一个带有 for 循环的 else 一样,我认为只使用 else 并且不允许 elif 是非常有意义的,elif 在那里表现类似于其他语言中的 switch/case 语句。

来自 gossamer-threads 上的旧线程 Why no 'elif' in try/except? :

Because it makes no sense?

The except clauses are for handling exceptions, the else clause is for handling the case when everything worked fine.

Mixing the two makes no sense. In an except clause, there is no result to test; in an else clause, there is. Is the elif supposed to execute when there are exceptions, or when there aren't? If it's simply an extension to the else clause, then I suppose it doesn't harm anything, but it adds complexity to the language definition. At this point in my life, I tend to agree with Einstein - make everything as simple as possible, but no simpler. The last place (or at least one of the many last places) I want additional complexity is in exception handling.

你总是至少需要一个 if 来使用 elif,它只是无效的语法。唯一可能最终未定义的是 value,您应该使用 if/else 将逻辑移到 try/except 中:

try:
value = next(e["value"] for e in my_list if e["name"] == name)
if value % 2:
print("Odd !")
else:
print("Even !")
except StopIteration:
print("Uuuh not found.")

如果 value = next... 错误,您的 print("Uuuh not found.") 将被执行,如果不是您的,那么您的 if/else 将被执行。

你可以有多个 elif,但你必须以 if 开头:

if something:
...
elif something_else:
....
elif .....

另一种选择是使用 next 的默认值,然后使用 if/elif/else,如果我们没有找到匹配的名称 next 将返回 None 所以我们检查 if value is not None,如果是我们打印 "Uuuh not found." 否则我们得到一个匹配的名字所以我们去 elif/否则:

value = next((e["value"] for e in my_list if e["name"] == name), None)
if value is None:
print("Uuuh not found.")
elif value % 2:
print("Odd !")
else:
print("Even !")

关于python - 为什么 Python 不在 try 语句上实现 elif 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32115375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com