-1

I was hoping someone could explain what the comma in between 'n' and 'digit' does.

while n > 0:
     n, digit = divmod(n, 10)
     total_sum = total_sum + digit ** 2
return total_sum

I've seen the comma been used in other situations and had always thought that, in this case, it meant that n and digit were equal to divmod(n, 10). I tried to see if the code still works but it doesn't so that doesn't seem to be the case. Could anyone explain what the comma in between the n and digit is denoting?

gkh
  • 1
  • 1

5 Answers5

0

divmod returns a tuple of two numbers (the devisor and remainder). Using the comma syntax allow you to assign those numbers to two different varaibles.

Tom Ron
  • 5,906
  • 3
  • 22
  • 38
0

The Python assignment statement supports not only individual assignment but also assignment to a list of targets. This is commonly known as unpacking, as the elements of a ride-hand-side iterable are extracted and assigned to the names of the target list.

>>> a, b = 1, 2
>>> print(a)
1
>>> a, b = range(2)
>>> print(a)
0

In specific, the divmod(a, b) function returns a tuple of a // b, a % b. Assigning to two targets assigns each term to a separate variable.

>>> div, mod = divmod(1024, 10)
>>> print(div)
102
>>> print(mod)
4
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
0

n is the Quotient and digit is the remainder . let me show a example

n=25 and other is 10

Quotient = 2

Remainder = 5

gulbaz khan
  • 175
  • 1
  • 9
0

It translates to:

"I expect the divmod function returns something that has exactly two parts, save me some time by getting those two parts into variables named n and digit".

The divmod returns two numbers. While you could do something like:

x = divmod(n, 10)
n = x[0]
digit = x[1]

the above one-liner is far better.

Also, you can do stuff like this:

ls = ["myValue"]
(value,) = ls
print(value) #prints: myValue

To unpack a value from a list with single element.

tornikeo
  • 915
  • 5
  • 20
0

divmod is a divide and mode, and it return the result divided and the remaining of number(here n is number and 10 is the divider)

n, digit = divmod(10,3)
n = 3
digit = 1

When you divide 10 to 3 the result is 3 and the remaining is 1

KayseMca
  • 40
  • 1
  • 6