If I want to find the sum of the digits of a number, i.e.:
932
14
, which is (9 + 3 + 2)
you can also try this with built_in_function called divmod() ;
number = int(input('enter any integer: = '))
sum = 0
while number!=0:
take = divmod(number, 10)
dig = take[1]
sum += dig
number = take[0]
print(sum)
you can take any number of digit
The best way is to use math.
I knew this from school.(kinda also from codewars)
def digital_sum(num):
return (num % 9) or num and 9
Just don't know how this works in code, but I know it's maths
If a number is divisible by 9 then, it's digital_sum will be 9,
if that's not the case then num % 9
will be the digital sum.
You can try this
def sumDigits(number):
sum = 0
while(number>0):
lastdigit = number%10
sum += lastdigit
number = number//10
return sum
If you want to keep summing the digits until you get a single-digit number (one of my favorite characteristics of numbers divisible by 9) you can do:
def digital_root(n):
x = sum(int(digit) for digit in str(n))
if x < 10:
return x
else:
return digital_root(x)
Which actually turns out to be pretty fast itself...
%timeit digital_root(12312658419614961365)
10000 loops, best of 3: 22.6 µs per loop
Try this
print(sum(list(map(int,input("Enter your number ")))))
n = str(input("Enter the number\n"))
list1 = []
for each_number in n:
list1.append(int(each_number))
print(sum(list1))