pythonsyntax-erroraugmented-assignment

Augmented assignment in the middle of expression causes SyntaxError


In my code I have these lines:

if numVotes == 0:
    avId in self.disconnectedAvIds or self.resultsStr += curStr

When I run the code I get this error?

SyntaxError: illegal expression for augmented assignment

How do I fix this error?


Solution

  • The assignment

    self.resultsStr += curStr
    

    is a statement. Statements can not be part of expressions. Therefore, use an if-statement:

    if avId not in self.disconnectedAvIds:
        self.resultsStr += curStr
    

    Python bans assignments inside of expressions because it is thought they frequently lead to bugs. For example,

    if x = 0    # banned
    

    is too close too

    if x == 0   # allowed