Why is print(x += 1) invalid syntax?

Question:

This works just fine

x = 0
while True:
    x += 1
    print(x)

while this

x = 0
while True:
    print(x += 1)

doesn’t

I want a program that counts to infinity or at least until max digits

Asked By: cryptoboomer

||

Answers:

Because the argument to print() needs to be an expression, and an assignment statement is not an expression.

The walrus operator := was introduced in Python precisely to allow you to do this, though it does not have a variant which allows you to increment something. But you can say

x = 0
while True:
    print(x := x + 1)

This does not strike me as a particularly good or idiomatic use of this operator, though.

Answered By: tripleee

Unlike many other languages, where an assignment is an expression and evaluates to the assigned value, in Python an assignment is its own statement. Therefore it can’t be used in an expression.

One advantage of this is that if you forget an = in an if statement (i.e. you meant to write == but wrote = instead) you get an error:

if a = b:   # this is an assignment not a comparison! SyntaxError

In certain other languages this is valid syntactically but wouldn’t give you the result you intend, causing hair-loss bugs. (This is one reason linters were invented. The language itself didn’t prevent you from making this mistake, so they created an external tool to help with that.)

Python 3.8 adds the assignment operator, :=, a.k.a. the walrus operator. It behaves like assignment in other languages, although you still can’t use it everywhere. So this works:

x = 0
while True:
    print(x := x + 1)

Unfortunately (or fortunately) there is no +:=, which I guess you’d call an augmented walrus.

Answered By: kindall
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.