Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

BeginnerPhase 2 - Level 1: Basic LoopingExample 10 of 14
product-of-digits-with-a-basic-while-loop.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Calculate product of digits
5product = 0 if num == 0 else 1
6temp = abs(num)
7
8while temp > 0:
9 digit = temp % 10
10 product *= digit
11 temp //= 10
12
13print(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. 1

    Set the initial product using the zero-input case.

  2. 2

    Scan abs(num), multiplying each units digit.

  3. 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.