21.5 Combining branching with loops
- Page ID
- 88714
And now for the really important application of branching in data science programs: combining it with loops.
Just as we can have an if statement (or if/else, or if/elif/else) inside an if body, so we can have an if statement (and friends) inside a loop body. This is where we’re going to get a lot of mileage.
Let’s return to Springfield. Our simpsons DataFrame from p. 174 looked like this:
Now an ordinary loop could print (say) the name and favorite things of all the characters:
Code \(\PageIndex{1}\) (Python):
for row in simpsons.itertuples():
print("{} likes {}.".format(row.Index, row.fave))
Output:
But combining this with branching techniques gives us more power. We could, for example, print only the females:
Code \(\PageIndex{2}\) (Python):
for row in simpsons.itertuples():
if row.gender == "F":
print("{} likes {}.".format(row.Index, row.fave))
Output:
or give different messages for different age ranges:
Code \(\PageIndex{3}\) (Python):
for row in simpsons.itertuples():
if row.age >= 18:
print("{} earns ${} outside the home.".format(row.Index, row.salary))
else:
print("Aw, {}'s just a kid.".format(row.Index))
Output:
or combine these things in innumerable ways:
Code \(\PageIndex{4}\) (Python):
for row in simpsons.itertuples():
if row.species == "human":
if row.IQ > 115:
print("We'd like to nominate {} for a Nobel prize.".format(row.Index))
elif row.IQ >= 90:
print("You can trust {} with a {}, or even a knife.".format(row.Index, row.fave))
else:
print("Hmm. No comment.")
if row.salary > 0:
print("The {}-year-old {} is gainfully employed.".format(row.age, row.Index))
else:
print("Hey...{} is some kind of animal!".format(row.Index))
Output:
You get the idea. Using a loop, we can successively consider each element of an array/Series or the rows of a DataFrame. Using if and friends, we can treat each one differently depending on its characteristics. The possibilities are endless!