Python Program to find largest and smallest digit of a number using the function


In this program, You will learn how to find the largest and smallest digit of a number using a function in Python.


1234 => 4 1

Example: How to find the largest and smallest digit of a number using a function in Python.

def largest(n):
    digit = 0

    while n > 0:
        r = n % 10
        if digit < r:
            digit = r
        n = int(n / 10)
    return digit


def smallest(n):
    digit = 9

    while n > 0:
        r = n % 10
        if digit > r:
            digit = r
        n = int(n / 10)

    return digit


x = int(input("Enter a number:"))

result = largest(x)
print("Largest digit is:", result)

result = smallest(x)
print("Smallest digit is:", result)

Output:

Enter a number:3245
Largest digit is: 5
Smallest digit is: 2