34-4 Use of return in for loop

In the assignment Linear Search with Modular Code of the Algorithms course, the right code is

def player_age(name):
    for row in nba:
        if row[0]==name:
            return row[2]
    return -1

Why doesn’t this work?:

def player_age(name):
    for row in nba:
        if row[0]==name:
            return row[2]
        else: 
            return -1

Thanks for helping!

Hey, Margot.

To make it easier to understand what’s going on, let’s work with a subset of the data:

>>> nba = [row[:3] for row in nba[:5]]
>>> print(*nba, sep="\n")
['Quincy Acy', 'SF', '23']
['Steven Adams', 'C', '20']
['Jeff Adrien', 'PF', '27']
['Arron Afflalo', 'SG', '28']
['Alexis Ajinca', 'C', '25']

Now let’s create your function:

>>> margot_def player_age(name):
...     for row in nba:
...         if row[0]==name:
...             return row[2]
...         else: 
...             return -1

And let’s use it:

>>> margot_player_age("Margot")
-1

So far, so good. Let’s use the name displayed above instead:

>>> margot_player_age("Quincy Acy")
'23'

Still working properly. Let’s now try using any other name:

>>> margot_player_age("Alexis Ajinca")
-1

It didn’t return Alexis’ age. So what happened here? Let’s breakdown what your function did:

  • The input is Alexis Ajinca
  • It begins by iterating over nba using the variable row.
  • Since the first entry in nba is ['Quincy Acy', 'SF', '23'], this means row is exactly this entry.
  • It then checks to see if row[0] is equal to input, which is Alexis Ajinca.
  • Since row[0] is Quincy Acy and Quincy Acy is not equal to the input, it will execute the else statement.
  • The else statement returns -1 and the execution of the function stops.

Whenever a function finds a return statement, it returns whatever it needs to return and it stops the execution of the function right there.

I’ll let you figure out why the given solution works.

Hi Bruno,

Thank you very much for the very clear explanation! It is so easy if you explain it like this!

Best Margot

1 Like