gpt4 book ai didi

python - 检查 Python 中的初始化变量

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

我是 Python 的新手,正在尝试一些代码片段。

在我的代码中,我需要检查变量初始化,我使用了这个习惯用法:

if my_variable:
# execute some code

但阅读一些帖子我发现使用了另一个成语:

if my_variable is not None:
# execute some code

它们是等价的还是有一些语义差异?

最佳答案

引用 Python documentation on boolean operations ,

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

因此,if my_variable 将失败,如果 my_variable 具有上述任何虚假值,而第二个仅当 my_variable 时才会失败> 是 。通常情况下,变量使用 None 作为占位符值进行初始化,如果在程序中的某个时间点不是 None 那么他们就会知道已经分配了一些其他值

例如,

def print_name(name=None):
if name is not None:
print(name)
else:
print("Default name")

这里,函数 print_name 需要一个参数。如果用户提供它,则它可能不是 None,因此我们打印用户传递的实际名称,如果我们不传递任何内容,则默认为 None将被分配。现在,我们检查 name 是否不是 None 以确保我们正在打印实际名称而不是 Default name

注意:如果你真的想知道你的变量是否被定义,你可能想试试这个

try:
undefined_variable
except NameError as e:
# Do whatever you want if the variable is not defined yet in the program.
print(e)

关于python - 检查 Python 中的初始化变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27962668/

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