Smallest & Largest Digit

Find smallest and largest digit of a number.

AdvancedPhase 2 - Level 5: Logical Loop CombinationsExample 5 of 12
smallest-largest-digit.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Find smallest and largest digit
5temp = abs(num)
6smallest = 9
7largest = 0
8
9while temp > 0:
10 digit = temp % 10
11 if digit < smallest:
12 smallest = digit
13 if digit > largest:
14 largest = digit
15 temp //= 10
16
17print(f"Smallest digit: {smallest}")
18print(f"Largest digit: {largest}")

Output

Enter a number: 45231
Smallest digit: 1
Largest digit: 5

What's going on

Track smallest and largest while processing digits.

Key Concepts:

Initialize smallest to 9, largest to 0
Update as you process each digit
Compare and update values