Jan Kowalski Jan Kowalski - 9 months ago 17
Python Question

or in if statement - one condition of the two met

This is my code:

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

# path == "/api/"

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

Why my
is not displayed?


Your print statement is in fact always displayed. That's because at least one of the two tests will always be true. If the path starts with one string, it can't start with another, so if one of the two conditions is false, the other is certainly going to be true:

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

You probably want to use and instead, so both tests must be true:

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

or use parentheses and one not, i.e. only execute the print if the path does not start with either option:

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