n=input("Enter a Number :")
my_sum=0
for i in range(0,len(n)):
my_sum=my_sum+int(n[i])
print("Sum of digits in number : ", my_sum)
Output
Enter a Number :549
sum of digits in number : 18
In above code we used len() to get the number of elements ( or char here ) in the string object n.
n=int(input("Enter a Number :"))
my_sum=0
while(n>0):
i=n%10 # reminder value of division
my_sum=my_sum+i
n=n//10 # floor value of division
print("sum of digits in number=",my_sum)
Output
Enter a Number :1251
sum of digits in number=9
n=int(input("Enter a Number :"))
total=0
def my_sum(n):
global total
if n<=0:
return 0
else:
i=n%10 # reminder value of division
total=total+i
n=n//10 # floor value of division
my_sum(n) # Using recursive function
return total
print("sum of digits in number = ",my_sum(n))
We are using recursive function here. Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.