Product of Digits with a Basic While Loop
Multiply a number's digits using a basic while loop. Students trace abs, remainder, floor division, and the zero case that needs a separate initial value.
1# Take number2num = int(input("Enter a number: "))34# Calculate product of digits5product = 0 if num == 0 else 16temp = abs(num)78while temp > 0:9 digit = temp % 1010 product *= digit11 temp //= 101213print(f"Product of digits: {product}")
Output
Enter a number: 234 Product of digits: 24
In this one
- Use a multiplication identity
- Extract and remove digits
- Handle literal zero
How it works
- 1
Set the initial product using the zero-input case.
- 2
Scan abs(num), multiplying each units digit.
- 3
Remove digits with floor division and print product.
Edge cases
What if a digit is zero?
What if a digit is zero?
The product becomes zero.
Are negative signs multiplied?
Are negative signs multiplied?
No. abs removes the sign before digit extraction.
What's going on
This digit product uses a shrinking copy of the input. abs removes the sign, % 10 extracts the rightmost digit, and // 10 removes that digit.
product begins at one and is multiplied by each extracted digit. For 234, the successive products are four, twelve, and twenty-four. Zero needs explicit handling because its loop has no iterations; its digit product should be zero, not the untouched one.
What if a digit is zero? The product becomes zero.
Are negative signs multiplied? No. abs removes the sign before digit extraction.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which operation removes a digit?
Pick an answer to check it.
Question 2
What if a digit is zero?
Pick an answer to check it.
Questions people ask
What if a digit is zero?
The product becomes zero.
Are negative signs multiplied?
No. abs removes the sign before digit extraction.
Which operation removes a digit?
Integer floor division by ten.
๐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