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


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
    return res


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)
    return soma


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.