在Python中如何测试变量是否为None、True或False
我有一个函数,它可以返回三种结果:
- 成功(
True
) - 失败(
False
) - 读取/解析流时出错(
None
)
我想问的是,如果我不应该直接检查 True
或 False
,那我该怎么判断结果呢?下面是我现在的做法:
result = simulate(open("myfile"))
if result == None:
print "error parsing stream"
elif result == True: # shouldn't do this
print "result pass"
else:
print "result fail"
是不是只要去掉 == True
的部分就可以了,还是说我应该添加一个三值数据类型?我不想让 simulate
函数抛出异常,因为我只希望外部程序在遇到错误时记录一下,然后继续运行。
6 个回答
13
这里有很多不错的回答。我想再补充一点。如果你在处理数字的时候,结果恰好是0,那么你的代码里可能会出现错误。
a = 0
b = 10
c = None
### Common approach that can cause a problem
if not a:
print(f"Answer is not found. Answer is {str(a)}.")
else:
print(f"Answer is: {str(a)}.")
if not b:
print(f"Answer is not found. Answer is {str(b)}.")
else:
print(f"Answer is: {str(b)}")
if not c:
print(f"Answer is not found. Answer is {str(c)}.")
else:
print(f"Answer is: {str(c)}.")
Answer is not found. Answer is 0.
Answer is: 10.
Answer is not found. Answer is None.
### Safer approach
if a is None:
print(f"Answer is not found. Answer is {str(a)}.")
else:
print(f"Answer is: {str(a)}.")
if b is None:
print(f"Answer is not found. Answer is {str(b)}.")
else:
print(f"Answer is: {str(b)}.")
if c is None:
print(f"Answer is not found. Answer is {str(c)}.")
else:
print(f"Answer is: {str(c)}.")
Answer is: 0.
Answer is: 10.
Answer is not found. Answer is None.
252
if result is None:
print "error parsing stream"
elif result:
print "result pass"
else:
print "result fail"
保持简单明了。当然,你可以提前定义一个字典。
messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]
如果你打算修改你的 simulate
函数,加入更多的返回代码,维护这段代码可能会变得有点麻烦。
而且,simulate
可能会因为解析错误而抛出异常,这种情况下你要么在这里捕获这个异常,要么让它往上层传播,这样打印的部分就可以简化成一行的if-else语句。
136
别害怕异常!让你的程序记录错误并继续运行其实很简单:
try:
result = simulate(open("myfile"))
except SimulationException as sim_exc:
print "error parsing stream", sim_exc
else:
if result:
print "result pass"
else:
print "result fail"
# execution continues from here, regardless of exception or not
现在,当你在模拟方法中遇到问题时,可以得到更详细的通知,这样如果你觉得仅仅知道有没有错误不够有用,就能更清楚地知道到底出了什么问题。