Python Practice › Loop Programs › Program 19

Count the digits of a number

EasyLoop Programs · 19 of 90

Write a Python program to count the digits of a number.

Advertisement
Input
908172
Output
Digits: 6

Approach

  1. Divide by 10 until the number becomes 0, counting the steps.

Solution

Python
n = 908172count = 0while n > 0:    n //= 10    count += 1print("Digits:", count)
Output
Digits: 6

Line by line

Line 4

Each //= 10 removes one digit.

Tip

len(str(abs(n))) gives the same answer for non-zero numbers.

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs

Leave a Comment