Exercise
Numerical Digits
Objective
Develop a Python program to calculate the number of digits in a positive integer (hint: this can be done by repeatedly dividing by 10). If the user enters a negative integer, the program should display a warning message and proceed to calculate the number of digits for the equivalent positive integer.
For example:
Number = 32
2 digits
Number = -4000
(Warning: it is a negative number) 4 digits
Example Python Exercise
Show Python Code
# Prompt the user to enter a number
num = int(input("Please enter a number: "))
# Check if the number is negative
if num < 0:
print("Warning: it is a negative number")
num = abs(num) # Convert the number to its positive equivalent
# Initialize the digit counter
digits = 0
# Use a while loop to count the number of digits
while num > 0:
num //= 10
digits += 1
# Display the number of digits
print(f"{digits} digits")
Output
Please enter a number: 32
2 digits
Please enter a number: -4000
Warning: it is a negative number
4 digits
Share this Python Exercise