lvcasco
lvcasco

Reputation: 45

What does this Python line mean?

I came across this line in a Python code and don't know how what it does:

do_update = error !=0

This was the context, the code was a perceptron classifier:

    def update(self, instance):
    """
    Perform perceptron update, if the wrong label is predicted.
    Return a boolean value indicating whether an update was performed.
    """
    error = 0
    predicted_output = self.prediction(instance.feature_counts)
    if(predicted_output==True and instance.label==False):error = 1
    if(predicted_output==False and instance.label==True):error = -1

    do_update = error !=0

    if do_update:
        for feature, count in instance.feature_counts.items():
            self.weights[feature] += error*count
    return do_update

Can someone explain how it works?

Upvotes: 1

Views: 586

Answers (3)

jambrothers
jambrothers

Reputation: 1590

error !=0 is a Boolean expression and will return True if error does not hold the value 0, and False otherwise. It might help to add brackets:

do_update = (error != 0)

Upvotes: 0

Arount
Arount

Reputation: 10403

This is a quick way to store the result of a check.

Because error != 0 returns bool, do_update is False or True.

Bascially, if error is 0, do_update is False, else do_update is True.

Upvotes: 0

Mike Scotty
Mike Scotty

Reputation: 10782

do_update = error !=0

Means: evaluate error !=0 and assign the result to do_update.

The evaluation of error !=0 will be a boolean (True / False), based on the value of error.

Specifically:

if error equals 0, do_update will be False

if error is not equal 0, do_update will be True

Upvotes: 2

Related Questions