The sum of digits adds every decimal digit of a number. For 549, the answer is 5 + 4 + 9 = 18. Python can calculate it by iterating through a string or using % 10 and // 10.
Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.
View on GitHubn = "549"
my_sum = 0
for digit in n:
my_sum += int(digit)
print("Sum of digits:", my_sum)
Output:
Sum of digits: 18
The string approach follows the original lesson and makes the digits easy to see.
input() returns text. Convert each character into an integer before adding it.
n = input("Enter a Number :")
my_sum = 0
for i in range(len(n)):
my_sum += int(n[i])
print("Sum of digits in number:", my_sum)
Output:
Sum of digits in number: 18
n % 10 returns the final digit, and n // 10 removes it. This is the arithmetic approach from the original page.
n = 1251
my_sum = 0
while n > 0:
digit = n % 10
my_sum += digit
n //= 10
print("Sum of digits:", my_sum)
Output:
Sum of digits: 9
Return a value so other calculations can reuse it.
def digit_sum(n):
n = abs(n)
total = 0
while n:
total += n % 10
n //= 10
return total
for value in (0, 549, -1251):
print(value, digit_sum(value))
Output:
0 0
549 18
-1251 9
A recursive method processes the last digit, then the remaining number. Returning the result avoids mutable global state.
def recursive_digit_sum(n):
n = abs(n)
if n < 10:
return n
return n % 10 + recursive_digit_sum(n // 10)
print(recursive_digit_sum(1251))
Output:
9
A generator expression is concise, although the loop is usually clearer for beginners.
n = -7092
answer = sum(int(ch) for ch in str(abs(n)))
print(answer)
Output:
18
Convert input carefully. Negative numbers can use abs(); reject decimal points unless you deliberately want to include fractional digits.
raw = "12x"
try:
n = int(raw)
print(sum(map(int, str(abs(n)))))
except ValueError:
print("Enter a whole number")
Output:
Enter a whole number
input() returns a string. Convert and validate the value before doing arithmetic.Try changing 549 to 12345, then compare the loop, recursive and one-line answers. Use the companion practice notebook for runnable examples and self-checks.
No. Apply abs(n) so a negative number uses the same digits as its positive counterpart.
Zero.
Start with the string for loop, then learn modulo and floor division.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.