-2

This function is supposed to return the sum of all the digits in a number.

def sum_digits(num):
    if int(num) <= 0:
        return 0
    else:
        sum = 0
        while int(num) != 0:
            n = int(num) % 10
            num = int(num) / 10
            sum = int(sum + n)
        return sum 

It works fine for smaller numbers, but if i enter for example number 999999999999999999999999999999999 it returns 74 instead of 297.

Thanks for help

leo997
  • 3
  • 3

2 Answers2

0

You need to divide with (//) instead of (/), because that would return a floating number. You need to do something like this:

def sum_digits(num):
    num = int(num)
    if num <= 0:
        return 0
    else:
        sum = 0
        while num != 0:
            n = num % 10
            num //= 10
            sum +=  n
        return sum

(I reformated your code a little for better readability.)

edit: typo fixed

danyroza
  • 154
  • 1
  • 10
-1

I approached your problem a little different

number = 999999999999999999999999999999999
    number = str(number)
    sum = 0
    for digit in number:
        digit = int(digit)
        sum = digit+sum
    print(sum)