This guide explains Track Minimum and Maximum Values in a Loop through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
Finding a minimum or maximum in a loop requires a meaningful initial value, usually the first item. Initializing the minimum to zero fails when all actual values are positive.
When You Would Use This
Find the smallest and largest temperatures in a set of readings.
Step-by-Step Example
temperatures = [12, 19, 8, 16]
minimum_temperature = temperatures[0]
maximum_temperature = temperatures[0]
for temperature in temperatures[1:]:
if temperature < minimum_temperature:
minimum_temperature = temperature
if temperature > maximum_temperature:
maximum_temperature = temperature
print(minimum_temperature, maximum_temperature)
How the Example Works
The algorithm begins at 12, then updates the maximum to 19 and minimum to 8. The result is 8 and 19.
Example Output
8 19
Try It Yourself
Modify the list so all readings are negative and verify the result.
Common Beginner Mistakes
- Initializing the minimum to zero when all values are positive.
- Accessing the first element of an empty list.
- Using
elifwhen a value might need to update both extrema in special initial states.
Key Takeaways
- Finding a minimum or maximum in a loop requires a meaningful initial value, usually the first item.
- The algorithm begins at 12, then updates the maximum to 19 and minimum to 8.
- Avoid this mistake: Initializing the minimum to zero when all values are positive.