Home > Blockchain >  Why is print(x = 1) invalid syntax?
Why is print(x = 1) invalid syntax?

Time:01-07

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

CodePudding user response:

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. 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.

CodePudding user response:

The syntax print(x = 1) is invalid because the = operator is an assignment operator, not a comparison operator.

The print() function expects to receive a value to print, not an assignment.

In the first example, you are correctly assigning the value of x 1 to x and then printing the value of x. In the second example, you are trying to print the result of an assignment, which is not allowed.

CodePudding user response:

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.

  • Related