Doubts about how to iterate


I am having trouble with this exercise, can anybody help??

Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number’s digits. For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that the number you are given will always be positive.)


at this point, you learned the for loop, the while loop and range(), some of this must be useful for looping?


Take a look at the hint. Think about when you were iterating a string. You’d loop through each character and then do something. What if you use that same approach here? Makes sense, right? You want to iterate each digit.

How would you do that? Let’s go back to how you iterate each character in a string:

for char in "1234":
    # do something

Your function receives a number. How can you iterate it as a string? The hint tells you.

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.

Give that a try.


And then taking @stetim94 reply, the 2nd part of the hint gives you a 2nd approach to the problem. You can use the while loop to loop through the number.

  1. Then use modulo 10, i.e. num % 10 to get the rightmost digit.
  2. And remove the rightmost digit using floor divide, e.g. num //= 10.

Like anything in code, there are multiple ways to solve the same problem.

See if you can try both approaches.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.