Count the Number of Occurrences of digit in a number using Python

Get a number and a digit and find occurrences of digit in the number.

Sample Input 1:

Enter the number: 2434

Enter the Digit : 4

Sample Output 1:

4 is occurred 2 times in 234 

Sample Input 2:

Enter the number: 974

Enter the Digit : 3

Sample Output 2:

3 is occurred 0 times in 974

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

#write your code here

Program or Solution

				
				
					

num = int(input("Enter the number"))

digit = int(input("Enter a Digit"))

count = 0

n = num

while n != 0:

    rem = n % 10

    if rem == digit:

        count+=1

    n = n // 10

print("{} occured {} times in {}".format(digit,count,num))

Program Explanation

initialize count is equal to 0

calculate the remainder of a number by doing number % 10

check remainder is equal to digit, if it is equal increment the count by 1 , else divide number by the 10 and repeat the above steps till number becomes zero.

print the count.

Comments