mbubb
mbubb

Reputation: 13

Python while loop. What is this construct called?

On the Literate Programs site, I was looking at the Python code for the GCD algorithm.

def gcd(a,b):
        """ the euclidean algorithm """
        while a:
                a, b = b%a, a
        return b

What is going on in the body? Expression evaluation? Is it a compressed form of another structure?

Upvotes: 1

Views: 80

Answers (3)

bgporter
bgporter

Reputation: 36514

There are two things going on here:

            a, b = b%a, a

First, a tuple is created with the contents (b%a, a). Then the contents of that tuple are unpacked and assigned to the names a and b.

Upvotes: 2

julienc
julienc

Reputation: 20325

a is receiving the result of b%a while b is receiving the value of a

Works the same as:

while a > 0:
    tmp = a
    a = b%a
    b = tmp
return b

See this post for more information on switching variables: Is there a standardized method to swap two variables in Python?

Upvotes: 0

Andrew
Andrew

Reputation: 5083

Looks like shorthand for:

while a > 0:
    temp = a
    a = b%a
    b = temp
return b

Upvotes: 1

Related Questions