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.
1# Take number2num = int(input("Enter a number: "))34# Count digits5count = 06temp = abs(num)78if temp == 0:9 count = 110else:11 while temp > 0:12 count += 113 temp //= 101415print(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
Store abs(num) in temp.
- 2
Set count one for zero; otherwise count removals.
- 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.
๐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