[Python] How does Python know to associate variables with their respective names?

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    I don't have a problem with code not working, but rather, seeking to understand why it works. Specifically, I don't understand how the program moves from a list of tuples in one part of the program (in this case, athletes and their respective ages and positions all together in a tuple), and then somehow "knows" where each associated value belongs down in another part of the program. I'm just missing some understanding in the syntax I guess and would appreciate any pointers. Here's the sample code:

    team = [('Marta', 20, 'center'), ('Ana', 22, 'point guard'), ('Gabi', 22, 'shooting guard'), ('Luz', 21, 'power forward'), ('Lorena', 19, 'small forward'), ]

    def player_position(players):
    result = []
    for name, age, position in players:
    result.append('Name: {:>19} \nPosition: {:>15}\n'.format(name, position))
    return result

    for player in player_position(team):
    print(player)


    How does Python know that we want it to look in the "team" list for all the data? The new function that we are defining, player_positions, is taking one argument: "players". Where did this argument come from? It just showed up in the middle of the code, and didn't get explicitly defined or assigned anywhere that I can see. How does Python know to associate this argument "players" with all the data recorded inside the list of tuples?

    Continue reading...

Compartilhe esta Página