4/15 Why is it throwing "math domain error".It gives right answer when called


#1

import math
def digit_sum(num):
    res = 0
    n = num
    a = (math.log(num))/(math.log(10))+1
    while a>=1:
        res += n%10
        n = (n - n%10)/10
        a-=1
    return res

#2

def digit_sum(n):

 soma =0
    n_string = str(n)
    tam = len(n_string) ##number of digits
    for i in n_string:
        soma += int(i)
    print(soma)
    return soma

#3

You will get that error when the log function computes a negative number for some inputs. To prevent this you might wanna use a try/except block.