The Largest Value
The third pattern finds the largest value. Imagine going through a pile of exam papers to find the best one. You pick up the first paper. Then you look at the others one by one, and whenever one is better than the paper in your hand, you take that one instead. At the end, you are holding the best paper. In code, the paper in your hand is a variable:
scores = [72, 45, 90, 38, 64]
highest = scores[0]
for score in scores:
if score > highest:
highest = score
print("Highest score:", highest)Highest score: 90The variable highest starts with the first element. Then the loop compares each score with it: 72 is not greater than 72, 45 isn't either, but 90 is, so highest becomes 90. Neither 38 nor 64 is greater than 90, so 90 stays until the end.
Why not start with 0? Because 0 might not be one of the values. If all the values were negative, for example winter temperatures [-5, -2, -8], the starting 0 would remain the largest, and the program would print 0, a temperature that isn't in the list at all. The first element is always a safe start.
You find the smallest value the same way, only with < instead of >.
Python has shortcuts for these too: max() gives the largest value of a list, and min() the smallest:
scores = [72, 45, 90, 38, 64]
print(max(scores))
print(min(scores))90
38Use them whenever you simply need the largest or the smallest value. The loop is for when you need something more, for example the longest name in a list: there, you compare len(name), but keep the name itself.
Instructions
The list prices holds the prices of headphones in an online shop. Create a variable highest with the first price, prices[0].
Go through prices with a loop, and whenever a price is greater than highest, store it in highest. After the loop, print the result with print("Most expensive:", highest). The output is Most expensive: 2499.
Find the price of the cheapest headphones with Python's shortcut: print Cheapest: and min(prices). The output is Cheapest: 179.
Start programming for free
6/11