Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14096

Assignments in conditions

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

Answers (3)

inspectorG4dget
inspectorG4dget

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

Mike McMahon
Mike McMahon

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

user2555451
user2555451

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

Related Questions