You’re seeing Python’s ability to do multiple assignments.
You know the simple assignment and it is easy to understand. to the left of the assignment signal =
there is the name of a variable and on the right side, after that operator, there is an expression that will generate a value that will be assigned to the variable.
In this case you have more than one variable on the left side, so you must have in one way or another the generation of more than one value. It may be that a single expression generates different values or it may be multiple expressions.
In the specific case it has two variables and two expressions. Then the first expression will be the value assigned to the first variable, while the second is assigned to the second variable.
This is a curious example because it still does something we call swap. It exchanges values at the same time. So when executing the value of y
is now assigned to x
and the value of y
becomes a calculation of the rest of x
divided by y
. Obviously the value of y
used in the first assignment is the value before changing right away. And the value of x
used in the second expression is the value x
previous, not what made the previous assignment.
It can be written that way too:
def testes(x, y):
while y:
temp = x
x = y
y = temp % y
return x
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Interesting. So, all values on the right side are calculated before any assignment.
– G. Bittencourt
Exactly. Python values short codes.
– Maniero
Another detail is that
while y:
means that asy
is not zero the loop will not stop running. In this case, with each iteration the variabley
receive a lower value until zero.– Marcio Rodrigues
def tests(x, y): while y: x, y = y, x % y Return x # in this case on line 3. x = y and y = x % y so x will show the result of x % y that’s it?
– TiadoDev
@Tiadodev will have a process there, but in the end it will end up being the result of the penultimate rest. Now you can vote on everything on the site also.
– Maniero