Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

++i operator in Python

Tags:

java

python

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?

like image 890
user2016462 Avatar asked Feb 27 '13 06:02

user2016462


People also ask

What is i operator in 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.

What is += i in Python?

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.


1 Answers

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!

like image 58
wim Avatar answered Sep 27 '22 19:09

wim