欢迎各位兄弟 发布技术文章
这里的技术是共享的
python 判断 变量为空
在 Python 中,判断变量是否为空(empty)通常需要根据变量的具体类型来决定检查方式。以下是常见场景和判断方法:
not
或 if not var
pythonif not var: print("变量为空或为假值")
适用场景:适用于大多数情况(会同时判断 None
、空容器、False
、0
等)。
注意:此方法会捕获所有“假值”(Falsy values),包括:
None
空容器([]
, {}
, ()
, ""
, set()
)
False
数值 0
或 0.0
None
pythonif var is None: print("变量是 None")
适用场景:明确需要检查 None
时(不包含其他空值)。
字符串:
pythonif not var.strip(): # 检查空字符串或仅包含空白字符 print("字符串为空或仅包含空格")
列表/字典/集合/元组:
pythonif len(var) == 0: # 或直接 if not var: print("容器为空")
数值:
pythonif var == 0: # 明确检查 0 print("数值为 0")
None
和未定义变量
若变量可能未定义,需用 try-catch
或 globals()
/locals()
:
pythontry: if var is None: print("变量存在,值为 None") except NameError: print("变量未定义")
Pandas 的 NaN
或 NumPy 的空值:
pythonimport pandas as pd import numpy as np if pd.isna(var) or np.isnan(var): # 检查 NaN print("变量是 NaN")
pythondef is_empty(var): if var is None: return True elif isinstance(var, (str, list, dict, set, tuple)): return len(var) == 0 elif isinstance(var, (int, float)): return var == 0 else: return not bool(var) # 兜底判断 # 测试 print(is_empty(None)) # True print(is_empty("")) # True print(is_empty([])) # True print(is_empty(0)) # True print(is_empty("Hello")) # False
根据你的具体需求选择合适的判断方式!
global last_time
if not last_time:
last_time = time.time()
print(last_time)
File "D:\pythonProject4\self_installation\self_installation_ok.py", line 290, in update_progress
if not last_time:
NameError: name 'last_time' is not defined
这个错误是因为你使用了变量 last_time
,但没有在函数内部或全局作用域中定义它。Python 找不到这个变量,所以抛出 NameError
。
last_time
没有被赋值或声明为全局变量(global last_time
)之前,你就尝试访问它。
即使你写了 global last_time
,但 last_time
从未被赋值过,if not last_time
仍然会报错,因为变量未定义。
last_time
(推荐)如果你想在全局作用域使用 last_time
,确保它已经定义:
pythonimport time last_time = None # 先初始化全局变量 def update_progress(): global last_time # 声明使用全局变量 if not last_time: # 第一次调用时 last_time 是 None,条件成立 last_time = time.time() print(last_time) update_progress() # 输出当前时间戳
try
捕获异常如果 last_time
可能未定义,可以捕获异常:
pythonimport time def update_progress(): global last_time try: if not last_time: # 如果 last_time 未定义,跳转到 except last_time = time.time() except NameError: last_time = time.time() # 初始化 print(last_time) update_progress() # 输出当前时间戳
hasattr
检查全局变量是否存在如果你不确定 last_time
是否已定义,可以检查:
pythonimport time def update_progress(): global last_time if not hasattr(update_progress, 'last_time'): # 检查是否已初始化 last_time = time.time() print(last_time) update_progress()
✅ 推荐方法 1:先全局初始化 last_time = None
或 last_time = 0
,再使用 global
修改它的值。
❌ 避免:直接 if not last_time
而不确保 last_time
已经定义。
如果你想让 last_time
在函数调用之间保持状态,可以:
全局变量(如示例)
类属性(更规范的 OOP 方式)
函数属性(update_progress.last_time = time.time()
)
你可以根据需求选择最合适的方式!