I'm new to python. In C/C++, inside the while or if statement, I did variable assignments quite often. The following is a simple example code in C++:
#include <iostream>
int Increment(const int x) {
return (x + 1);
}
int main(void) {
int x = 2, y;
while ((y = Increment(x)) > 2) {
std::cout << "y is larger than 2" << std::endl;
}
return (0);
}
But the following python code doesn't work:
#!/usr/bin/python
def Increment(x):
return x + 1
def main():
x= 2
while (y = Increment(x)) > 2:
print "y is larger than 2"
if __name__ == "__main__"
main()
The error message is as follows:
while (y = Increment(x)) > 2:
^
SyntaxError: invalid syntax
It seems that in python, it is not possible to do a variable assignment inside the comparison statement right? Then, what would be the best way to do this in python?
def main():
x = 2
y = Increment(x)
while y > 2:
print "y is larger than 2"
y = Increment(x)