0

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)
chanwcom
  • 4,420
  • 8
  • 37
  • 49

4 Answers4

7

The difference between Python and C (or C++) is that in Python assignment is a statement, while in C (and C++) assignment is an expression.

Expressions can be part of other expressions, but statements are stand-alone.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

No, but you can (have to) bind to a variable in a for loop. So for your example, try to stop thinking in C/C++ and start thinking in Python: use a for loop and move the condition part of the while into a generator.

Unfortunately your example doesn't actually do anything useful and loops forever, but most real examples will quickly simplify into something much cleaner than you would get with a while.

With the example given you don't even need a generator, just iterate the calls to Increment(x).

#!/usr/bin/python

def Increment(x):
  return x + 1

def main():
  x= 2
  for y in iter(lambda: Increment(x)):
      if y <= 2: break
      print "y is larger than 2"

if __name__ == "__main__"
  main()

If there was a fixed return from the function that indicated completion (eg. None for end of data) then the two argument version of iter() is useful and you don't need the separate check:

>>> def collatz(x):
    if x%2:
        return 3*x+1
    return x//2

>>> x = 5
>>> for y in iter(lambda: collatz(x), 1):
    print(y)
    x = y


16
8
4
2

And the generator version of that would be:

>>> def collatz(x):
    while x != 1:
        x = 3*x+1 if x%2 else x//2
        yield x

>>> for y in collatz(7):
    print(y, end=' ')


22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 

which neatly separates the complex loop logic from the action we want to do on each iteration.

Duncan
  • 92,073
  • 11
  • 122
  • 156
2

Rather than repeat the call to Increment(), I would structure the loop this way:

x = 2
while True:
    y = Increment(x);
    if not y > 2:
        break
    print "y is larger than 2"

This is also discussed in The Python design FAQ, which suggests the same code.

The FAQ also mentions using iteration:

for y in itertools.repeat(Increment(x)):
    if not y > 2:
        break
    print "y is larger than 2"

Or:

from itertools import takewhile, repeat
for y in takewhile(lambda y: y > 2, repeat(Increment(x)):
    print "y is larger than 2"

This code doesn't actually call Increment each time around the loop, it relies on the knowledge that it's the same value every time. But as in Duncan's answer, you can for example use iter with a lambda to change that. Something of the sort would be necessary if x is modified in the loop. Any of the following will do the iteration, and depending how the real code differs from this example you might want to base your code on any of them. For example, itertools.repeat(x) is easily changed to itertools.count(x) or xrange(x) or any other iterator, whereas in iter(lambda: x) the x is easily changed to any other expression you like.

itertools.repeat(Increment(x))
iter(lambda: Increment(x))
itertools.imap(Increment, itertools.repeat(x))
itertools.imap(Increment, iter(lambda: x))

You can then apply itertools.takewhile to any of them.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
0

There is no way to assign variables in expressions in Python.

However, since your loop loops forever, and Increment(x) has no side-effects, you can just do this (it is identical in behaviour):

def main():
    while True:
        print("y is larger than 2")