gpt4 book ai didi

python - 我是否必须在 Python 中引发 ValueError

转载 作者:太空狗 更新时间:2023-10-30 01:44:07 26 4
gpt4 key购买 nike

我有这个代码:

chars = #some list

try:
indx = chars.index(chars)
except ValueError:
#doSomething
else:
#doSomethingElse

我希望能够做到这一点,因为我不喜欢故意引起异常:

chars = #some list

indx = chars.index(chars)

if indx == -1:
#doSomething
else:
#doSomethingElse

我有办法做到这一点吗?

最佳答案

请注意,后一种方法违背了普遍接受的 EAFP, or "It is Easier to Ask for Forgiveness than Permission." 的“pythonic”哲学。 , 而前者紧随其后。

关于python - 我是否必须在 Python 中引发 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/131449/

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