gpt4 book ai didi

python - 在 Python 中,没有结果返回什么,False 或 None?

转载 作者:行者123 更新时间:2023-11-28 21:59:27 35 4
gpt4 key购买 nike

我有一个搜索查询结果的函数。如果没有结果,建议返回什么,False 还是 None?

我想这不是那么重要,但我想遵循最佳实践。

最佳答案

A positive result would be a short string in this case.

假设你有这样的(极其微不足道的)例子......

the_things = {'foo', 'bar'}

def find_the_thing(the_thing):
if the_thing in the_things:
return the_thing

...如果找不到该东西,默认会返回None,这没关系,你可以这样使用...

the_thing = find_the_thing('blah')
if the_thing is not None:
do_something_with(the_thing)
else:
do_something_else()

...但有时像这样引发异常会更好...

the_things = {'foo', 'bar'}

def find_the_thing(the_thing):
if the_thing in the_things:
return the_thing
raise KeyError(the_thing)

...你可以像这样使用...

try:
do_something_with(find_the_thing('blah'))
except KeyError:
do_something_else()

...这可能更具可读性。

关于python - 在 Python 中,没有结果返回什么,False 或 None?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16594103/

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