Slice18
Slice18

Reputation: 5

Python Summing variables in a list

So I'm trying to make a text adventure, and I'm attempting to keep track of stats by using list.

So for example I have:

User_stats = []
User_weapon = ""
User_armor = ""

Sword = 10
Pike = 13
Crude = 2
Heavy = 5

print (weapons)
print ("First lets pick a weapon,(enter the type of weapon, not the name)")
User_weapon = input() 
User_stats.append(User_weapon)
print (armor)
print("Now lets pick some armor (enter the first word of the armor)")
User_armor = input ()
User_stats.append(User_armor)
print (User_stats)

which prints the list of what the user chose such [Sword, Crude]. Is there a way to pull the values off of those variables and sum them (in order to determine if an attack succeeds or not)?

Thanks for any help!

Upvotes: 0

Views: 137

Answers (4)

0xhughes
0xhughes

Reputation: 2753

Considering all of your variables are integers I would imagine a simple adding process would work.

for item in User_stats:
    SUM = item + SUM

It should iterate through your stat list and add each value to the SUM variable.

Upvotes: 0

thegrinner
thegrinner

Reputation: 12241

It might be a bit easier if you use dictionaries to track the weapon/armor types:

weapons = {"Sword": 10, "Pike": 13}
armor = {"Crude": 2, "Heavy": 5}

You can then access their values more directly for summing:

test = ["Sword", "Crude"]
test_val = weapons[test[0]] + armor[test[1]]

Upvotes: 0

poke
poke

Reputation: 388153

You should have some kind of dictionary for this which holds the relation weapon/armor type to value:

weapons = { 'Sword': 10, 'Pike': 13 }
armors = { 'Crude': 2, 'Heavy': 5 }

Then when you know the user has choosen a weapon, you can just get the value using weapons['Sword'] or with your variables weapons[User_Weapon] or even weapons[User_stats[0]].

Upvotes: 1

TehTris
TehTris

Reputation: 3217

dictionaries may be what you want.

>>>weapons = {'axe': 2, 'sword': 1 }
>>>weaponMods = {'crude': -1, 'amazing': 20 }
>>>print weapons['axe']
2
>>> print weapons['axe'] + weaponMods['crude']
1

Upvotes: 0

Related Questions