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

Count Digits in a Number

Count decimal digits in an integer by repeatedly dividing by ten. Students trace a Python while loop, ignore a negative sign, and handle zero as one digit.

IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 1 of 14
count-digits-in-a-number.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Count digits
5count = 0
6temp = abs(num)
7
8if temp == 0:
9 count = 1
10else:
11 while temp > 0:
12 count += 1
13 temp //= 10
14
15print(f"Number of digits: {count}")

Output

Enter a number: 12345
Number of digits: 5

Enter a number: 0
Number of digits: 1

In this one

  • Count integer positions
  • Ignore a negative sign
  • Treat zero as one digit

How it works

  1. 1

    Store abs(num) in temp.

  2. 2

    Set count one for zero; otherwise count removals.

  3. 3

    Repeatedly divide temp by ten and print count.

Edge cases

How many digits does zero have here?

How many digits does zero have here?

One, through the explicit zero branch.

Does -120 have four digits?

Does -120 have four digits?

No. abs removes the sign, leaving three decimal digits.

What's going on

Counting digits in an integer means removing one decimal position at a time, not scanning text for numeric characters. abs first removes a possible negative sign.

Each //= 10 shortens temp and adds one to count. Input 120 takes three iterations. Zero is handled separately because the while condition would otherwise skip its single written digit. Leading zeros cannot survive conversion to int.

How many digits does zero have here? One, through the explicit zero branch.

Does -120 have four digits? No. abs removes the sign, leaving three decimal digits.

Quiz

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

Question 1

What advances the loop toward stopping?

Pick an answer to check it.

Question 2

How many digits does zero have here?

Pick an answer to check it.

Questions people ask

How many digits does zero have here?

One, through the explicit zero branch.

Does -120 have four digits?

No. abs removes the sign, leaving three decimal digits.

What advances the loop toward stopping?

temp //= 10.