[Tutor] Variable help
python at venix.com
Sun Oct 8 19:40:53 CEST 2006
On Sun, 2006-10-08 at 10:40 -0300, Ismael Garrido wrote:
> Tom R. escribió:
> > I have a number of arrays:
> > player1 = [data, data, data]
> > player2 = [data, data, data]
> > player3 = [data, data, data]
> > player4 = [data, data, data]
> > I want to be able to do something like:
> > count = 2
> > if player + count == 5:
> > do this
> > do that
> > count += 1
> > And that would do this and that to the array 'player2' in slot 3. It adds 1
> > to 'count', so next time through it will access the array 'player3'.
> > Basically I want to be able to integrate the value of one variable into
> > another variables name. It's hard explain, hopefully the code above will
> > give you an idea of what I'm trying to achieve.
> Put the players in a list.
> player_list = [player1, player2, player3... ]
> So if you want to get to player1 data, you use player_list[0...2],
> which would be the same as player1[0...2].
> If you then want to do something to every player, you could do:
> for player in player_list:
> do something
> > Alternately, how can I use the return of a function as a variables name? eg:
> > def choose_player(player):
> > if player == 1:
> > return player1[3
> > if player == 2:
> > return player2
> > if player == 3:
> > return player3
> > if player == 4:
> > return player4
> > choose_player(2) = 5
> Functions return values. To keep the return value, you simply have to
> assign it to a variable:
> result = choose_player(3)
> And then you can do whatever you want with result. Bear in mind that
> result and player3 are *not* the same thing, they only have the same
(let me offer a correction to that last sentence.)
result = player3 # player3 must contain at least 4 values
result and player3 *do* reference the same thing. My preferred
analogy is that names in Python are written on sticky notes and stuck on
the objects they refer to. The name and the object are separate and
distinct. So we take a sticky note labeled result and stick it on the
*same* object that player3 refers to.
If that object is immutable, then it can't be changed and you can only
bind result or that position in the player3 list to different things.
Both bindings are independent. HOWEVER, both start off referring
(bound) to the same thing.
If we have a succeeding line that says:
result = 4
The "result sticky note" is peeled off the original object and stuck
onto the the "4 object". player3 is not affected.
This distinction between value and object reference becomes important
when the object is mutable. Then lines like:
affect player3 because both are actually bound to the same object.
> Tutor maillist - Tutor at python.org
More information about the Tutor