Learn about Number of Digits in a Number in Python using Recursion in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.
Number of Digits in a Number in Python using Recursion
The recursion technique can also be used to count the number of digits in a number. Recursion is a method of defining a function that includes a call to itself. The recursive function allows us to break down a complex problem into identical single simple cases that we can easily handle.
Program:
# Python program to count number of digits in a number
# Function for count number of digits
count = 0
def count_Digits(num):
global count
if(num > 0):
count = count + 1
count_Digits(num // 10)
return count
# input
num = int(input('Enter any number: '))
# printing number of digits
print('Number of digits:', count_Digits(num))
Output:
Enter any number: 456
Number of digits: 3
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : Count Number of Digits in a Number using Math Module