2021-12-01

Can i make this recursion work with negative numbers

I wrote this code and it's alright with positive numbers, but when I tried negative it crashes. Can you give any hints on how to make it work with negative numbers as well? Also, I need it with recursion. The function needs to calculate the sum of the digits of an integer.

def sum_digits(n):
    if n != 0:
        return (n % 10 + sum_digits(n // 10))
    else:
        return 0
    
if __name__=='__main__':
    
    print(sum_digits(123))


Input: 123
Output: 6


from Recent Questions - Stack Overflow https://ift.tt/3G4GMSu
https://ift.tt/eA8V8J

No comments:

Post a Comment