Python program to Calculate the sum of the digits in an integer
Method 1:-
num = int(input("Input a four digit numbers: "))
a = num //1000
a1 = (num - a*1000)//100
a2 = (num - a*1000 - a1*100)//10
a3 = num - a*1000 - a1*100 - a2*10
print("The sum of digits in the number is", a+a1+a2+a3)
output:-
Input a four digit numbers: 1246
The sum of digits in the number is 13
Method 2:-
def sumDigits(no):
return 0 if no == 0 else int(no % 10) + sumDigits(int(no / 10))
# Driver code
n = int(input("Input a four digit numbers: "))
print(sumDigits(n))
output:-
Input a four digit numbers: 123
6
Method 3:-
def getSum(n): sum = 0 while (n != 0): sum = sum + (n % 10) n = n//10 return sum n = int(input("Input a four digit numbers: ")) print(getSum(n))
output:-Input a four digit numbers: 14545 19
Method 4:-
def getSum(n):
sum = 0
for digit in str(n):
sum += int(digit)
return sum
n = int(input("Input a four digit numbers: "))
print(getSum(n))
output:-Input a four digit numbers: 13243
13
Post a Comment
If you have any doubts, Please let me know
Thanks!