In this tutorial, we will learn how to count the number of digits present in a number in Python. We will cover the basic concept of number manipulation and implement a function to perform the counting.
Number manipulation involves performing operations on numbers to achieve a specific result. Counting the number of digits in a number is a common task in number manipulation.
The syntax to count the number of digits in a number in Python is:
def count_digits(n):
return len(str(n))
We can create a function to count the number of digits in a given number by converting it to a string and getting the length of the string.
For example,
count_digits
that takes one parameter n
.str
function.len
function.def count_digits(n):
return len(str(n))
# Sample number
sample_number = 12345
# Count the number of digits
result = count_digits(sample_number)
# Print the result
print('Number of digits in', sample_number, 'is:', result)
Number of digits in 12345 is: 5