Thursday, 30 April 2026

πŸš€ Day 35/150 – Count Digits in a Number in Python

 

πŸš€ Day 35/150 – Count Digits in a Number in Python

Counting digits means finding how many digits are present in a number.

Examples:
12345 → 5 digits
900 → 3 digits
0 → 1 digit

Let’s explore different ways to count digits in Python πŸ‘‡

πŸ”Ή Method 1 – Using while Loop

count = 0 while n > 0: n //= 10 count += 1  

print("Digits:", count)



 digit at a time using integer division.

πŸ”Ή Method 2 – Taking User Input




n = int(input("Enter a number: ")) count = 0 temp = abs(n) while temp > 0: temp //= 10 count += 1 print("Digits:", count)










✅ Works with negative numbers too.

πŸ”Ή Method 3 – Using String Method

n = 12345 count = len(str(abs(n))) print("Digits:", count)




✅ Easiest and most beginner-friendly method.

πŸ”Ή Method 4 – Using Recursion

def count_digits(n): n = abs(n) if n < 10: return 1 return 1 + count_digits(n // 10) print(count_digits(12345))









✅ Great for learning recursive logic.

🎯 Output

Digits: 5

πŸ”‘ Key Takeaways

  • Use // 10 to remove the last digit step by step.
  • len(str(n)) is the easiest way to count digits.
  • Use abs(n) to handle negative numbers.
  • Special case: 0 has 1 digit.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (255) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (29) Azure (10) BI (10) Books (262) Bootcamp (11) C (78) C# (12) C++ (83) Course (87) Coursera (300) Cybersecurity (30) data (5) Data Analysis (32) Data Analytics (22) data management (15) Data Science (354) Data Strucures (17) Deep Learning (158) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (73) Git (10) Google (51) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (42) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (292) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (14) PHP (20) Projects (33) pytho (1) Python (1333) Python Coding Challenge (1132) Python Mathematics (1) Python Mistakes (51) Python Quiz (491) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (49) Udemy (18) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)