The number 987654321 has 9 digits. This page counts them with a loop, and then with a string.
The program
python
n = int(input("Enter a whole number: ")) number = abs(n) count = 0 while True: count += 1 number //= 10 if number == 0: break print(f"{n} has {count} digits")
Typed in this example: -98765. Press Run to type your own.
output
Enter a whole number: -98765 -98765 has 5 digits
How it works
number //= 10removes the last digit. The program counts how many times it can do this before the number becomes 0.- The digit is counted before the check, so the loop always runs at least once. This makes 0 count as 1 digit. A plain
while number > 0:loop would give 0 digits for the number 0, which is wrong. abs(n)removes the minus sign, because the sign is not a digit.
Another way: len(str())
python
for n in [987654321, -98765, 0, 7]: print(n, len(str(abs(n))))
output
987654321 9 -98765 5 0 1 7 1
str() turns the number into text and len() counts the characters. Without abs(), len(str(-98765)) would be 6, because the minus sign is a character too.