How to test a variable is null in python
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 | val ="" del val if val is None: print("null") |
我运行了以上代码,但得到了
如何判断变量是否为空,避免名称错误?
测试指向
检查
1 2 | if val is None: pass # val exists and is None |
要检查名称是否存在:
1 2 3 4 | try: val except NameError: pass # val does not exist at all |
1 2 3 4 5 6 7 | try: if val is None: # The variable print('It is None') except NameError: print ("This variable is not defined") else: print ("It is defined and has a value") |
您可以在尝试捕获块中执行此操作:
1 2 3 4 5 | try: if val is None: print("null") except NameError: # throw an exception or do something else |