Sum of Digits
Add the decimal digits of an integer with Python modulo and floor division. Students follow a running total, a shrinking copy, and sign-independent digit sums.
1# Take number2num = int(input("Enter a number: "))34# Sum of digits5digit_sum = 06temp = abs(num)78while temp > 0:9 digit = temp % 1010 digit_sum += digit11 temp //= 101213print(f"Sum of digits: {digit_sum}")
Output
Enter a number: 1234 Sum of digits: 10
In this one
- Sum digit values
- Use floor division
- Preserve the source input
How it works
- 1
Initialize a total and absolute working copy.
- 2
Add temp % 10, then remove that digit.
- 3
Continue to zero and print digit_sum.
Edge cases
What happens for zero?
What happens for zero?
The loop is empty and the total correctly remains zero.
Does -409 produce a negative sum?
Does -409 produce a negative sum?
No. abs makes the digit scan sign-independent.
What's going on
digit_sum starts at zero and temp stores the absolute input. Each iteration adds the current units digit before removing it from temp.
For 409, the digits arrive as nine, zero, and four, giving thirteen. Their extraction order does not affect addition. The source number remains in num, so digit processing does not destroy the value originally entered.
What happens for zero? The loop is empty and the total correctly remains zero.
Does -409 produce a negative sum? No. abs makes the digit scan sign-independent.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is extracted by temp % 10?
Pick an answer to check it.
Question 2
What happens for zero?
Pick an answer to check it.
Questions people ask
What happens for zero?
The loop is empty and the total correctly remains zero.
Does -409 produce a negative sum?
No. abs makes the digit scan sign-independent.
What is extracted by temp % 10?
The current units digit.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum