Learn Python · lesson 21 of 60 · about 8 minutes
Finding and Counting
Look back at Sam's week of sleep: keep the best night so far, count the good nights, and remember with a flag whether any night was very short.
What you'll learn
- Track a maximum while looping
- Count items that match a rule
- Use a found flag
A week of sleep
Sam wants the assistant to look back at the week's sleep. Sam types one digit per night, like 6787566, and a for loop visits the digits one by one. Three questions need three different loop patterns: what was the best night, how many nights were good (7 hours or more), and was any night really short?
Three classic patterns
Most loops do one of a few jobs:
- Find the biggest: keep the best so far and replace it when you see something bigger
- Count: add 1 whenever an item matches
- Search: set a flag to False, then True if you find it
Biggest digit in a number
digits = "4719"
biggest = 0
for d in digits:
if int(d) > biggest:
biggest = int(d)
print(biggest)Output
9Step through it: the best night so far
best = 0
for hours in "596":
night = int(hours)
if night > best:
best = night
print(best)Output
9Counting and searching
word = "mississippi"
s_count = 0
found_p = False
for ch in word:
if ch == "s":
s_count += 1
if ch == "p":
found_p = True
print(s_count, found_p)Output
4 TrueAll three for Sam's week
sleep = "6787566"
best = 0
good = 0
tired = False
for hours in sleep:
night = int(hours)
if night > best:
best = night
if night >= 7:
good += 1
if night < 5:
tired = True
print(f"Best night: {best} h")
print(f"Good nights: {good} of {len(sleep)}")
if tired:
print("Time for an early night")
Output
Best night: 8 h
Good nights: 3 of 7Tip
For a quick yes/no search, Python also has the in operator: "p" in "mississippi" is True. Loops are for when you need more than yes or no.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.