[Tutor] Beginner - list not returning correct variable value

Alan Gauld alan.gauld at btinternet.com
Thu Mar 13 19:34:30 CET 2014


On 13/03/14 16:12, Marc Eymard wrote:

> In attached script, can somebody tell me why the values of the variables
> strenght_points, health_points, wisdom_points and dexterity_points stay
> at 0 value when 'printing' their value from the list attributes[]

Because when you create the list you use the *values* of those variables 
at the time you created the list. They do not track
the values of the variables after that so changing the variables
has no effect on the list.

But, looking at your list, it is a name and corresponding value.
That is the definition of a dictionary so, rather than having
a set of variables and trying to maintain a list reflecting
those, you should just use a dictionary.

So your code would start with:

#set variables
pool = 30
att_choice = None

attributes = {
         'strength':0,
         'health':0,
         'wisdom':0,
         'dexterity',0
}


Then instead of using the variables use:

while att_choice != '0':
     print('here proof that variables values are changing as expected:')
     print(attributes['strength'],attributes['health'],
           attributes['wisdom'], attributes['dexterity'],pool)

and

     if att_choice == '1':
       print('\nHow many strength points to add or remove?')
       points = int(input('Enter points here: '))
       attributes['strength'] += points
       pool -= points

and so on.

Then finally to output the values:

     print('\nYou have now the following attributes and points:\n')

     for i in attributes:
         print(i,'\t',attributes[i])



HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list