Reputation: 25
I have the following python function but I am confused about line number 2 (q, r = 0, n)
1 def div3(n):
2 q, r = 0, n
3 while r >= 3:
4 q, r = q+1, r-3
5 return q
div3(6)
If I run the function when the second line executes I get r=6, n=6, and q=0, why is this? I thought that when the function is first run that upon execution of the second line the values would be r=0 and q=6 and n=6? Does it have to do with the way q r and n are separated with commas?
Upvotes: 1
Views: 46
Reputation: 35512
The q, r = 0, n
line actually uses tuple unpacking. With parentheses, the line would look like (q, r) = (0, n)
, not q, (r = 0), n
. Basically, it creates the tuple (0, n)
, assigns the first element to q
, and the second to r
, so the code is equivalent to:
q = 0
r = n
Upvotes: 4