[Tutor] Using a list

Alan Gauld alan.gauld at btinternet.com
Sat May 30 21:39:27 CEST 2009


"Doug Reid" <rnrcreid at yahoo.com> wrote

> The tutorial I'm using is discussing list, tuples, and dictionaries.
> ...
> four attributes: Strength,Stamina, Wisdom, and Dexterity.
> The player should be able to spend points from the pool on
> any attribute and should also be able to take points from
> an attribute and put them back into the pool.

How would you describe a dictionary?
Can you see a way to apply it to the problem?

> I'm wondering if I'm doing this right or is their a
> different more practical way of accomplishing this.

There are many many ways of doing this, most of them more
practical than your approach. Why? Well, consider what happens
with your approach if we want to have more than one player.
Where would you store the attribute values? Would you create more
global variables? But howe many players might there be?
Can you see the problem?

> I tend to over complicate things sometimes.

Not so much overcomplicating but not thinking enough about
how to leverage the power in the tools you have been given.

#user menu
#variables used
dexterity=0
strength=0
stamina=0
wisdom=0
allot=None
creating=True
change=0
points=30

#list of attributes and their values
attributes=['dexterity=',dexterity ,'strength=',strength, 
'stamina=',stamina, 'wisdom=',wisdom]

It is a list but not of attributes. Its a list containing strings and
numbers alternating. The strings consist of an attribute name
and an equals sign. But you know about a collection type that
stores values against strings and allows you to retrieve those
values using the string as a key.


#creation loop
while creating:

choice=menu()
if choice=='0':
   print '\nThank you for using character creator.'
   end=raw_input('\n Press enter to end.')
   creating=False
elif choice=='1':#prints out list of attributes and their values
   for entry in attributes:
      print entry,

This will print

attribute=
value
attribute=
value

Not very pretty. But if you use a dictionary:

for item in dictionary:
    print item, '=', dictionary[item]

elif choice=='2':
allot=raw_input('''What attribute would you like to change?
Enter dex for dexterity, str for strength, etc. ''').lower()
if allot=='dex':
change=int(raw_input('How many points do you wish to allot? '))
attributes[1]=dexterity=+change
points=points-change
if allot=='str':
change=int(raw_input('How many points do you wish to allot? '))
attributes[3]=strength=+change

And this gets even more messy.
Again think how it would look with a dictionary...

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list