简体   繁体   中英

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?

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 .

Looks like shorthand for:

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM