Python:Logical Operators

From PrattWiki
Jump to navigation Jump to search

Logical operators in Python are those that link logical statements together and return True or False depending upon the nature of the logical operator and the value of the components. Many times, logical operators are used to link together the results of several relational operators.

Logical Operators

There are three main logical operators in Python:

Name Example in code Text description
NOT not A True if A is False; False if A is True
AND A and B True if both A and B are true
OR A or B True if either A or B (or both!) are true

There is also an exclusive or, XOR, which is True if one and only one component is True. Python lacks a command for this; instead, you can define one with:

def xor(a, b):
    return (a or b) and not (a and b)

or, for an arbitrary number of inputs,

def xor(*vals):
    out = False
    for val in vals:
        if val and not out:
            out = True
        elif val and out:
            return False
        
    return out

The following table shows the results of four different pairs of input values to the logical operators above:

A B not A not B A and B A or B xor(A, B)
False False True True False False False
False True True False False True True
True False False True False True True
True True False False True True False

Common Errors

The most common errors with logical operators involve the order of operations. In the absence of parenthesis, any NOT operations go first, followed by AND, then finally OR. The following two statements both evaluate to True because the and happens first:

True or False and False
False and False or True

On the other hand, the following two statements evaluate to False because the or is forced to happen first:

(True or False) and False
False and (False or True)

If there are multiple statements of the same kind, they evaluate from left to right.

Questions

Post your questions by editing the discussion page of this article. Edit the page, then scroll to the bottom and add a question by putting in the characters *{{Q}}, followed by your question and finally your signature (with four tildes, i.e. ~~~~). Using the {{Q}} will automatically put the page in the category of pages with questions - other editors hoping to help out can then go to that category page to see where the questions are. See the page for Template:Q for details and examples.

External Links

References