FAQ: Learn Python - Practice Makes Perfect - digit_sum

@chanato if you know what action you want to be doing there (and you better, otherwise who’s writing the code?) then you’re in a position to google it - how does a list support this action?

Also, if you use names that describe what their values represent then you won’t have to repeatedly look at the definitions of them to figure out which you want. It’s also very hard to spot mistakes with those names. Try to bring your code a little closer to English.

So, for example, since i is a digit… name it digit. And c is multiple digits… digits.

digits + digit

and the mistake is already apparent. adding between different shapes usually doesn’t make sense, adding is generally an operation where both sides have the same shape, like a list of numbers and a list of numbers, or two numbers, two whatevers.

One name there is acceptable, n, which is quite common to use for a number. similarly i is a common name for an index (but your i is not an index, so that’s misleading)

yeah i noticed later, i was having some trouble with this problem and i tried doing step by step and in the middle of it i thought that i needed lists.

1 Like

It doesn’t, i was having trouble with this one and in the middle of everything i tought i needed lists.
Thanks for your response.

Hello everyone!

I’m having trouble thinking of edge cases for my solution except for entering a negative number or a non-integer value. Any ideas? I want to think about how to improve my solution.

Here is my code:

from math import* #just in case we need math functions

def digit_sum(n):
  new_n = str(n)
  sum_numbers = 0
  for char in new_n:
    new_char = int(char)
    sum_numbers += new_char
  return sum_numbers

Thanks in advance!

If you literally do digits -> sum then there are no edge cases, but you’re right in that sending in other types (floats, for example) is non-sensical when extracting digits

1 Like

A post was split to a new topic: Digit sum

Programming in python makes me to think more like a human than computer for a very first time.
This is really strange, this is not machine codding anymore. More like explaining a human student how to solve a problem:

  • How to add digits in some random number - 325476 for example?
  • Treat the number as a row of signs “3”,“2”,“5”,“4”,“7”,“6” - not a number.
  • Then turn these signs again into single digit numbers, and add them.

Your student doesn’t even have to know how to divide / multiply.

Pls can anyone explain to me why I am getting -6 as the output from these codes:
Import math
K = math.floor
Print(k(5.2)) # output is 5.
Print(k(-5.2)) # out is -6

floor rounds down. The nearest integer below -5.2 is -6.

my solution
mod by 10 to get last digit
then divided by 10 until n less than 0

def digit_sum(n) :
  total = 0;
  while n > 0 :
    total += n % 10;
    n = n / 10
  return total

I tried finding a solution without using anything more than the hint, and I think I found one but it doesn’t seem to be recognized. It says the number 434 returns 10, but I think it returns 11. Am I missing something?

numbers = []
def digit_sum(n):
  while n > 9:
    digits = n % 10
    numbers.append(digits)
    n = n // 10
    if n < 10:
      numbers.append(n)
#digit_sum(434)
print sum(numbers)

I commented out the function call, but any number you type in returns the correct sum. Is it because the list is outside of the function?

EDIT fixed 3 typos

yes, its because the list is outside the function
numbers = [] should be inside the function
and return sum(numbers) should be at the end of the function

outside the function …
print( digit_sum(434) )
should print 11 to the screen if the rest of the function is correct

got it, thanks for the tip!

but do you also understand the significance of the changes suggest by janbazant?

What I take away from my tinkering around with the code is that if I needed that list populated for some other part of a larger piece of code, my original code would do that, while returning nothing additional. But if I want the function to spit out the sum, I have to modify it like janbazant suggested and make it return the sum, otherwise the function isn’t doing its job.

Both ways spit out the correct answer, but only one is doing so inside the function. In my original code, the function (as defined in the exercise) is incomplete. I’m not calling the function to get an answer, I’m asking the list for the answer. In addition to being inelegant, it’s an extra step.

2 Likes

Hello!

why is my code not working? it prints 0 then it prints the correct answer.

def digit_sum(n):
  
  su_m = []
  for i in range(0, len(str(n))):
      su_m.append(int(str(n)[i]))
  print sum(su_m)

Welcome back to the forums!

Your code should be working as intended. Perhaps you have something else written in the same program that might be printing that zero?

1 Like

im not sure why :frowning:

The answer is in the error message. return, not print.

When all we want is a single value, in this case a sum, it may be better to stick to read only of an iterable fashioned from the input. Tally up the values and return the total.

digits = str(n)
tally = 0
for digit in digits:
  tally += int(digit)
return tally

No added structure needed.

2 Likes

wow i feel silly, that solved the issue, thank you. do you know why the 0 was there?

1 Like