0

In Java, I can set a variable in a loop condition as such

String s;

while ((s=myFunction())!=null){
    System.out.println("It's there jim. "+s);
}

In this example, s would be set to whatever the result of myFunction() was. In Python, I know I can do it as

s = myFunction()
while s!=None:
   print "It's there jim",s
   s = myFunction()

but I would like to avoid doing this. Is there a way I can do the above Java code in Python?

ollien
  • 4,418
  • 9
  • 35
  • 58

2 Answers2

2

You can't do this in Python. In Java, an assignment = is an expression, and it evaluates to the value of the assigned variable. In Python, the = assignment is an statement, so it doesn't have a value (it just gets executed) and can not be used in the way you described (see this post for details). Even more, if you try to use an assignment in a place where an expression is expected, you'll get an error:

a = 0
(a = 10) + 1
=> SyntaxError: invalid syntax
Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • @ollien not really, it's a decision decision with other implications, for example: it allows named argument calls where you can say `func(a=0, b=1)` to specify the parameters `a` and `b`. if assignments were expressions, this wouldn't be doable in an unambiguous way. – Ryan Haining Aug 22 '14 at 00:38
1

You can use iter:

for s in iter(myFunction, None):
    print "It's there jim", s

print s

But it's confusing at first glance, so just stick to what you have.

Blender
  • 289,723
  • 53
  • 439
  • 496