Count Digits in a Number
Count digits in a number.
IntermediatePhase 2 - Level 2: Number-based Looping LogicExample 1 of 14
count-digits-in-a-number.py
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
What's going on
Repeatedly divide by 10 to remove digits.
Key Concepts:
Divide by 10 (integer division) to remove last digit
Count iterations until number becomes 0
Handle special case of 0
🔗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