user3765883
user3765883

Reputation: 325

Odd boolean expression

I'm trying to debug (rewrite?) someone else's Python/cherrypy web app, and I ran across the following 'if' statement:

if not filename.endswith(".dat") and (
    filename.endswith(".dat") or not filename.endswith(".cup")
):
    raise RuntimeError(
        "Waypoint file {} has an unsupported format.".format(
            waypoint_file.filename
        )
    )

I think this is the same as:

if not A and (A or not B):

If so, then:

I'm pretty sure that the intent of the if block is to warn the user that the extension of the file in question is neither .DAT nor .CUP, but it doesn't look to me that it actually executes that intent.

I think the if block should be:

if(not .DAT and not .CUP) = if not(.DAT or .CUP)

Is that correct?

Upvotes: 2

Views: 81

Answers (2)

Daweo
Daweo

Reputation: 36700

As you have two variables which could only have one of two values you can easily test each case, for example by doing

for a in [False, True]:
    for b in [False, True]:
        print(a, b)
        if not a and (a or not b):
            print("Condition hold")
        else:
            print("Condition does not hold")

which gives output

False False
Condition hold
False True
Condition does not hold
True False
Condition does not hold
True True
Condition does not hold

As you can see it does only hold when both are False, therefore it is equivalent to

if not a and not b:

However in this particular case you do not even needs 2 conditions, as endswith argument

can also be a tuple of suffixes to look for

therefore you can write

if not filename.endswith((".dat", ".cup")):
    print("Unsupported format")

Upvotes: 2

theotechnic
theotechnic

Reputation: 109

As far as I see, for the second expression to be even relevant to the statement, the first one

Not A

has to be true. Therefore, A is False.

Therefore, the second statement looks like this:

False Or Not B

For the second statement also to be true, therefore B has to be False.

So it is a complicated way of saying,

Not A and Not B

, which by De Morgans Law implies Not (A or B)

Upvotes: 1

Related Questions