2016-05-16 142 views
-1

这是我的代码:或if语句 - 一个两个条件满足

s = "/test" 
a = "/api/" 

# path == "/api/" 

if not request.path.startswith(s) or not request.path.startswith(a): 
    print "is's ok!" 

为什么我print不显示?

+2

你的'print'应该总是**显示这个逻辑,因为你的测试不能产生'False'。 –

回答

3

您的print声明实际上是总是显示。这是因为两次测试中至少有一次将始终为为真。如果路径以一个字符串开始,它不能与其他启动,因此,如果这两个条件之一是假的,另一种是肯定会是真的:

>>> def tests(path): 
...  print not bool(path.startswith('/test')) 
...  print not bool(path.startswith('/api/')) 
... 
>>> tests('/api/') 
True 
False 
>>> tests('/test') 
False 
True 
>>> tests('') # or any other string not starting with /test or /api/ 
True 
True 

你可能想使用and相反,所以测试必须是真实的:

if not request.path.startswith(s) and not request.path.startswith(a): 

或使用括号和一个not,即只执行print如果路径不以任一选项启动:

if not (request.path.startswith(s) or request.path.startswith(a)): 
+0

这并不意味着'print'会一直显示在OP的代码中吗? – interjay

+0

@interjay:它确实会一直显示。 OP没有正确测试他们的代码。 –

+0

@霍洛威:ick,忘了编辑那部分,谢谢你的提醒! –