An interactive introduction to programming in Python, for human beings and whoever else
Chapter 20
I’ll admit it: the assignment you ended last chapter with was kind of dumb. Really dumb, honestly.
I haaaaate Computer Science homework because it’s always like “write some code to sort this list of numbers,” when honestly someone much smarter than any of us already wrote that code and we can use it ourselves. If anyone ever tells you to sort numbers in Python, just huff loudly and point them to this:
numbers = [5, 2, 4, 7, 6] numbers = sorted(numbers) print(numbers)
So yes, counting ducks was dumb, because you can use len(ducks)
until the day you die! Maybe even afterward, depending on how advanced computers are at that point.
But so our hard work doesn’t go to waste, let’s improve on what we did. But first: run the code below to see that yes, "Leonard"
does start with Leo
. Then change the name to "Stewart"
and try it again!
name = "Leonard" if name.startswith("Leo"): print(name, "starts with Leo") else: print(name, "does not start with Leo")
Now you know about .startswith
.
It seems dumb, but I promise it mostly isn’t! Conditionals - if
statements - become super useful when we’re counting things in for loops. Sometimes you don’t want to count everything, you only want to count things that meet a certain condition.
Instead of incrementing every single time we go through our loop, we might stop and say hey, do we care about this one? Do wewant to count it? And then either count it or not. Let’s try to put that concept to work:
The loop below counts every duck. Use our new friend .startswith
and an if
statement to make it only count the ducks whose names start with Leo
.
ducks = ["Leonard", "Starburst", "Leopold", "Lackluster"] # Initial state: ZERO ducks count = 0 for duck in ducks: print("Looking at", duck) count = count + 1 # Answer: How many ducks? print("We found", count, "ducks like Leo")
Leo
.if
statement asking if the duck’s name starts with Leo
if
statement inside of the loop (indent it!)duck
, not name
:
at the end of the if
statementif duck.startswith("Leo"):
as your conditionalelse
here.for
, and another for the if
. count = count + 1
will be indented the most.if
will be count = count + 1
, but indented twice, so it’s inside of the if
Should we have looked at a complete example first? Maybe! Are we both still alive, even though we dove right in ? Yes!
Let’s push our luck and try again, this time starting with even less! Given the grades in the list below, how many students scored 85 or higher?
grades = [100, 100, 45, 89, 73, 43, 13, 85, 90, 55, 87, 52, 94, 70, 21]
85
or higher have we seen?count = 0
for
loop and the if
inside of the loop, but this time we’re checking if the number is 85
or abovegrade > 84
or grade >= 85
:
at the end of your if
statement, and indent the count
line!for grade in grades:
and if grade >= 85:
.count = count + 1
Excellent work! Those are both pretty typical ways of using for loops and counters, and we’ll see this pattern (and variations) again and again. For example, sometimes you don’t care about the number you counted, you care about the percentage instead.
Using the completed code from above as a starting point, what percentage of the class received an 85 or higher? We’ll only need to change one line!
grades = [100, 100, 45, 89, 73, 43, 13, 85, 90, 55, 87, 52, 94, 70, 21]
>= 85
grades already, but how can we easily count the total number of grades?len(grades)
, we don’t have to count them the hard way!count / len(grades)
will divide the number we counted by the total number of gradesround()
If this is starting to seem tough, I’m with you! These kinds of problems are one of the gatekeepers of learning to program - figuring out for loops and how to use them is one of the big parts where people get frustrated, shrug and walk away.
That doesn’t need to be you! Programming is tough stuff that doesn’t really make sense a lot of the time, and it isn’t going to be easy for anyone (except maybe unicorns).
If it makes you feel any better, you’re like 75% of the way to knowing absolutely everything important about programming1. Let’s take deep breaths and relax and keep on going. - I believe in you! Python believes in you! Unicorns believe in you!
Loops and lists can be tough to think and reason through, especially early on, so here’s my suggestion: if you found this part tough at all (which is probably most of you!), skip back to the beginning of talking about lists. Go through it again. Repeat the lists/loops section three times.
Yes, I know, it sounds super boring. I won’t pretend it isn’t! It might seem like a silly idea, but I promise it’s not that much of your time, and by the time you’re done you’ll feel a lot more comfortable with these concepts. Even mindlessly typing answers again and again will help you absorb the materials!
Once you’re ready, let’s hop on.
[1] My patented list of The Only Important Things in Programming is: variables, functions/methods, loops, dictionaries. Everything else is just putting those things together in various arcane ways. That means you only have one more thing to learn!
We got a little more practice at programming thinking, especially using conditionals inside of for loops. This allows us to only count some of our data points.