Python's Not (Just) For Unicorns

An interactive introduction to programming in Python, for human beings and whoever else

Chapter 20

Putting loops to work

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)

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")
  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")
  • Hint: Let’s print the duck’s name even if it doesn’t start with Leo.
  • Hint: We’ll need to add an if statement asking if the duck’s name starts with Leo
  • Hint: Add the if statement inside of the loop (indent it!)
  • Hint: If you’re cutting and pasting from the first example, note that the variable name is duck, not name
  • Hint: Be sure to put a : at the end of the if statement
  • Hint: Use if duck.startswith("Leo"): as your conditional
  • Hint: We don’t need to use an else here.
  • Hint: We’re going to need two levels of indenting! One for the for, and another for the if. count = count + 1 will be indented the most.
  • Hint: The next line after the 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]
  • Hint: Be sure to set up your initial state. Before we’ve counted grades, how many grades 85 or higher have we seen?
  • Hint: Since we haven’t looked at any grades, we start from zero. We’ll want to start with count = 0
  • Hint: Be sure to print out the final count when you’re done!
  • Hint: Add a for loop to go through each grade.
  • Hint: It’s the same as the problem up above, with the for loop and the if inside of the loop, but this time we’re checking if the number is 85 or above
  • Hint: We can use grade > 84 or grade >= 85
  • Hint: Make sure you put a : at the end of your if statement, and indent the count line!
  • Hint: We’ll use for grade in grades: and if grade >= 85:.
  • Hint: And, of course, 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]
  • Hint: You can re-use your code from above to count the number of grades 85 or higher
  • Hint: To get the percentage, we’ll want to divide the number we counted by the total number of grades
  • Hint: We counted the >= 85 grades already, but how can we easily count the total number of grades?
  • Hint: We can use len(grades), we don’t have to count them the hard way!
  • Hint: count / len(grades) will divide the number we counted by the total number of grades
  • Hint: The confetti comes out for the decimal version, but if we want to make it a normal-looking percentage, we can multiply the decimal version by 100, then round it with round()

Allll right, let’s take a breather.

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!

Chapter summary

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.