def equip(x):
global bag_sword
global bag_chest
global bag_gloves
global bag_helmet
while x == "iron sword" and "iron sword" in bag:
if bag_sword:
print "You can't have 2 weapons equipped!"
x = ""
print "\nYou equip the iron sword.\n"
bag.remove("iron sword")
bag_sword.append("iron sword")
When I run this the first time, it works fine, but when I run it a second time nothing happens.
bag_sword is a list
test code:
bag.append("iron sword")
if input1[:5] == "equip":
print input1[:5]
equip(input1[6:])
print input1[6:]
I type into the console 'equip iron sword'
I've tried using a variable in place of the input[]
(It isn't syntax)
asked May 28, 2016 at 20:18
Adam Burros
1211 gold badge2 silver badges11 bronze badges
-
You function reads and mutates global variables, so it won't necessarily do the same thing each time it is called. What do you want to happen?nwk– nwk2016年05月28日 20:20:38 +00:00Commented May 28, 2016 at 20:20
-
What this is supposed to do is add a weapon to bag_sword if nothing is there, and tell the player they' can't have 2 equipped if one is already there.Adam Burros– Adam Burros2016年05月28日 20:22:14 +00:00Commented May 28, 2016 at 20:22
2 Answers 2
Here is how you can make the function work as described:
bag_sword = []
def equip(x):
global bag_sword
if x == "iron sword":
if "iron sword" in bag_sword:
print "You can't have 2 weapons equipped!"
else:
bag_sword.append("iron sword")
print bag_sword # Prints "[]".
equip("iron sword") # Prints nothing. Puts the string "iron sword" in bag_sword.
print bag_sword # Prints "['iron sword']".
equip("iron sword") # Prints "You can't have 2 weapons equipped!". bag_sword is unchanged.
answered May 28, 2016 at 20:29
nwk
4,0601 gold badge24 silver badges22 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Adam Burros
I ended up fixing this with a few tweaks to yours. I don't know why I used a while loop, I've been at this for a few days now heh, thank you.
You can make nwk's solution more general (also try to get rid of global variables):
def equip(item, bag):
if item in bag:
print "You can't have 2 {}s equipped!".format(item)
else:
bag.append(item)
def main():
bag_sword = []
print bag_sword
equip("iron sword", bag_sword)
print bag_sword
equip("iron sword", bag_sword)
if __name__ == '__main__':
main()
It also seems to me that a dictionary or class would be a better alternative than several bag lists:
def equip(item, slot, inventory):
if inventory[slot] == item:
print 'Already equipped.'
else:
inventory[slot] = item
print item.capitalize(), 'equipped.'
def main():
inventory = {
'weapon': None,
'gloves': None,
}
equip('iron sword', 'weapon', inventory)
print inventory
equip('iron sword', 'weapon', inventory)
if __name__ == '__main__':
main()
answered May 28, 2016 at 21:29
skrx
20.5k5 gold badges37 silver badges51 bronze badges
Comments
lang-py