Sum of Digits of a Number

Category: Python Basics
Tags: Digits, Sum

Write a program that calculates the sum of the digits of a number. This program should take an integer as input and output the sum of its digits.

Example:

Input: 1234 

Output: 10

Input: 567 

Output: 18

You can calculate the sum of digits by repeatedly dividing the number by 10 and adding the remainder to the sum.

def sum_of_digits(n):
sum_digits = 0
while n > 0:
sum_digits += n % 10
n = n // 10
return sum_digits

print(sum_of_digits(1234)) # Outputs: 10
print(sum_of_digits(567)) # Outputs: 18

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!