Write a function called
digit_sumthat takes a positive integer
nas input and returns the sum of all that number’s digits. For example:
1 + 2 + 3 + 4. (Assume that the number you are given will always be positive.)
Check the hint if you need help!
So here’s what I have:
def digit_sum(n): sum(n)
Obviously I’m missing something. I also tried:
def digit_sum(n): for x in n:
…but then I ran out of ideas.
The hint tells me to convert something into a string… but I can’t wrap my head around why I’d do that; this is arithmetic.
One way might be to convert the integer to a string with
str(), iterate over it, and turn the substrings back into integers with
int()to do the addition.
If you’re looking for a challenge, try this: to get the rightmost digit of a number, you can modulo (%) the number by 10. To remove the rightmost digit you can floor divide (//) the number by 10. (Don’t worry if you’re not familiar with floor division—you can look up the documentation here. Remember, this is a challenge!)
Try working this into a pattern to isolate all of the digits and add them to a total.
What is a substring? I tried Googling it but didn’t understand the result.
Edit: I just realized I’m supposed to sum the digits of a number! To use the program’s example, it’s not
[1,2,3,4], it’s one thousand two hundred thirty-four.