1

The program below was more precise and shorter than mine, and thus more appealing. I understand mod (%), but the rest of the syntax on the line noted is confusing me. Does anyone know what this syntax is called or how it works?

The problem asked to create a function to find the greatest common divisor (gcd) for two integers, which is the largest number that divides both numbers without a remainder.

For example, the gcd of 20 and 12 is 4.

def gcd(x, y):
   while y != 0:
       (x, y) = (y, x % y)    ## What is happening here? What's this syntax called?
   return x 

Link to where I found this program: How to calculate a mod b in python?

Thank you so much for your help!

tRot
  • 75
  • 4

1 Answers1

1

You have stumbled upon tuple assignments!

In a nutshell, in python, You can assign groups of variables so long as you are assigning them from a structure with the same format

Here is a simpler illustration of what is happening:

a,b = 3,5
#a is now equal to 3 and b is now equal to 5
#You literally could go: 
#   a = 3
#   b = 5
#And it would be logically equivalent 
a+b

Returns

>>>8

In your function, you are assigning the value of y (the second parameter of the function) to the variable x, and updating the value of y to the remainder of x/y.

I hope this helps.

dsb4k8
  • 61
  • 3
  • `a, b = b, a` is NOT equivalent to `a = b; b = a`. – iz_ Jan 28 '19 at 04:09
  • @Tomothy32 You are correct! Did I communicate that the two statements in your comment WERE equivalent? If so, I did not mean to. I am not swapping values. I was illustrating that `a,b = const1, const2` is equivalent to assigning the value const1 to variable `a` and assigning the value of const2 to variable `b`. – dsb4k8 Jan 28 '19 at 04:40