Smallest & Largest Digit
Track the smallest and largest digits with Python. Students update two running extremes, handle negative magnitudes, and treat zero as a real digit.
1# Take number2num = int(input("Enter a number: "))34# Find smallest and largest digit5temp = abs(num)6smallest = 0 if temp == 0 else 97largest = 089while temp > 0:10 digit = temp % 1011 if digit < smallest:12 smallest = digit13 if digit > largest:14 largest = digit15 temp //= 101617print(f"Smallest digit: {smallest}")18print(f"Largest digit: {largest}")
Output
Enter a number: 45231 Smallest digit: 1 Largest digit: 5
In this one
- Track two extremes
- Choose decimal sentinels
- Handle zero input
How it works
- 1
Set initial smallest with the zero case and largest zero.
- 2
Compare each extracted digit against both extremes.
- 3
Remove the digit and report the final pair.
Edge cases
What are both extremes for zero?
What are both extremes for zero?
Both should be zero.
What about -482?
What about -482?
abs makes its digits equivalent to 482.
What's going on
smallest starts at nine and largest at zero, the extremes of decimal digit values. Each extracted digit can replace either stored extreme.
For 482, the minimum becomes two and maximum eight. abs removes a negative sign before scanning. Zero needs explicit treatment because the loop is skipped; leaving smallest at nine would report a digit that was never present.
What are both extremes for zero? Both should be zero.
What about -482? abs makes its digits equivalent to 482.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why initialize smallest to nine?
Pick an answer to check it.
Question 2
What are both extremes for zero?
Pick an answer to check it.
Questions people ask
What are both extremes for zero?
Both should be zero.
What about -482?
abs makes its digits equivalent to 482.
Why initialize smallest to nine?
Every decimal digit can be no greater than nine.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum