Reputation: 14096
In C-like languages, we can write a loop like that:
while ( a = func(x) ){
// use a
}
Is there any syntax in Python to do the same thing?
Upvotes: 1
Views: 40
Reputation: 113915
Python doesn't allow assignments in the place of boolean expressions. The "pythonic" way to do this would be:
def func(x):
if goodStuff:
return somethingTruthy
else:
return somethingFalsey
a = func(x)
while a:
# use a
a = func(x)
Upvotes: 0
Reputation: 8594
No python does not have this because you open yourself up to bugs like
if usr = 'adminsitrator':
# do some action only administrators can do
Where you really meant ==
and not =
Upvotes: 0
Reputation:
There is no direct equivalent because assignments are statements in Python, not expressions like in C.
Instead, you can do either this:
a = func(x) # Assign a
while a: # Loop while a is True
# use a
a = func(x) # Re-evaluate a
or this:
while True: # Loop continuously
a = func(x) # Assign a
if not a: # Check if a is True
break # Break if not
# use a
The first solution is less code, but I personally prefer the second because it keeps you from duplicating the a = func(x)
line.
Upvotes: 3