Digit Sum vs Product
Compare a positive integer's digit sum and digit product in Python. Students trace two accumulators, digit extraction, and why an unchanged copy is useful.
1# Take number2num = int(input("Enter a number (1-9999): "))34# Calculate sum and product of digits5digit_sum = 06digit_product = 17temp = num89while temp > 0:10 digit = temp % 1011 digit_sum += digit12 digit_product *= digit13 temp //= 101415# Compare16if digit_sum > digit_product:17 print("Sum is greater than product")18elif digit_sum < digit_product:19 print("Product is greater than sum")20else:21 print("Sum equals product")
Output
Enter a number (1-9999): 123 Sum equals product Enter a number (1-9999): 234 Product is greater than sum
In this one
- Maintain two accumulators
- Use a disposable digit copy
- Compare completed summaries
How it works
- 1
Initialize sum zero, product one, and temp.
- 2
Extract each digit and update both accumulators.
- 3
Compare the completed sum and product.
Edge cases
What happens when a digit is zero?
What happens when a digit is zero?
The product becomes zero and stays zero.
What happens for input zero here?
What happens for input zero here?
The loop is skipped, leaving sum zero and product one; zero is outside the prompted range.
What's going on
One scan can calculate two different summaries of the same digits. digit_sum starts at zero, while digit_product starts at one so multiplication does not erase the result immediately.
temp % 10 extracts a digit and temp //= 10 removes it. Both summaries use each digit before removal. For 123, the sum and product are both six, so the equality branch runs. The loop assumes a positive input as prompted.
What happens when a digit is zero? The product becomes zero and stays zero.
What happens for input zero here? The loop is skipped, leaving sum zero and product one; zero is outside the prompted range.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why start the product at one?
Pick an answer to check it.
Question 2
What happens when a digit is zero?
Pick an answer to check it.
Questions people ask
What happens when a digit is zero?
The product becomes zero and stays zero.
What happens for input zero here?
The loop is skipped, leaving sum zero and product one; zero is outside the prompted range.
Why start the product at one?
One leaves the first multiplied digit unchanged.
๐Related Content
- ๐
Phase 1 - Learn Concepts
Review Phase 1 concepts and explanations
- ๐
Phase 1 - Quiz
Test your Phase 1 understanding with quiz questions
- ๐ป
Phase 1 - All Practice Problems
Explore all practice problems for Phase 1
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum