I'm trying to translate one of my Java projects to Python and I'm having trouble with one certain line. The Java code is:
if (++j == 9)
return true;
What I think this is supposed to be in python is
if (j += 1) ==9:
return True
...but I am getting an error SyntaxError: invalid syntax
.
How can I translate this Java to Python?
Python Identity Operators Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator. Description. Example.
The Python += Operator. The Python += operator adds two values together and assigns the final value to a variable. This operator is called the addition assignment operator.
Yes, that is indeed a syntax error.
You probably want:
j += 1
if j == 9:
return True
The reason is because python requires an expression after the if
keyword (docs), whereas j += 1
is a statement.
And congratulations, you've just dodged a bullet - by not translating it to:
if (++j == 9):
return True
which is valid python code, and would almost certainly be a bug!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With