Skip to Main Content
Blog

Count Occurrences of a Digit in Python

Count Occurrences of a Digit in Python

Enter number: 141592653589793
Enter key: 5
Count: 3
def main():
    """
    Counts the number of occurrences of a digit in a number.
    """

    num = int(input("Enter number: "))
    key = int(input("Enter key: "))

    RADIX = 10
    if not (0 <= key < RADIX):
        print(f"Digit must be within 0 to {RADIX - 1}.")
        return
    if num == key == 0:
        print(1)
        return

    num = abs(num)
    ctr = 0
    while num != 0:
        unit = num % RADIX
        if unit == key:
            ctr += 1
        num //= RADIX

    print(ctr)


if __name__ == "__main__":
    main()