In the assignment Linear Search with Modular Code of the Algorithms course, the right code is
for row in nba:
Why doesn’t this work?:
for row in nba:
Thanks for helping!
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==name:
... return row
... return -1
And let’s use it:
So far, so good. Let’s use the name displayed above instead:
>>> margot_player_age("Quincy Acy")
Still working properly. Let’s now try using any other name:
>>> margot_player_age("Alexis Ajinca")
It didn’t return Alexis’ age. So what happened here? Let’s breakdown what your function did:
- The input is
- It begins by iterating over
nba using the variable
- Since the first entry in
['Quincy Acy', 'SF', '23'], this means
row is exactly this entry.
- It then checks to see if
row is equal to input, which is
Quincy Acy and
Quincy Acy is not equal to the input, it will execute 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.
Thank you very much for the very clear explanation! It is so easy if you explain it like this!