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

Product of Digits with an Explicit Zero Case

Calculate digit products with an explicit zero branch. Students contrast empty-loop behavior with a valid zero result while preserving negative-input handling.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 11 of 14
product-of-digits-with-an-explicit-zero-case.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Calculate product
5product = 1
6temp = abs(num)
7if temp == 0:
8 product = 0
9else:
10 while temp > 0:
11 digit = temp % 10
12 product *= digit
13 temp //= 10
14
15print(f"Product of digits: {product}")

Output

Enter a number: 234
Product of digits: 24

In this one

  • Separate zero from an empty product
  • Multiply digit values
  • Scan negative magnitudes

How it works

  1. 1

    If temp is zero, set product zero.

  2. 2

    Otherwise multiply every extracted digit into product.

  3. 3

    Remove one digit per iteration and print.

Edge cases

Why does input zero need a branch?

Why does input zero need a branch?

Its while loop would not run, leaving the initial product one.

What does 203 produce?

What does 203 produce?

Zero, because one of its digits is zero.

What's going on

This version decides the zero case before entering its digit loop. That prevents the multiplication identity one from being mistaken for the product of zero's single digit.

For nonzero magnitudes, every remainder ten is multiplied into product before integer division removes the digit. A zero anywhere inside the number also forces the final product to zero. abs makes -234 and 234 share the same product.

Why does input zero need a branch? Its while loop would not run, leaving the initial product one.

What does 203 produce? Zero, because one of its digits is zero.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does -234 produce?

Pick an answer to check it.

Question 2

Why does input zero need a branch?

Pick an answer to check it.

Questions people ask

Why does input zero need a branch?

Its while loop would not run, leaving the initial product one.

What does 203 produce?

Zero, because one of its digits is zero.

What does -234 produce?

24.