mjam94
mjam94

Reputation: 25

I don't understand why these variables have these values

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

Answers (1)

Aplet123
Aplet123

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

Related Questions