Lavellen Lavellen - 6 months ago 10
Python Question

Python function not working a second time

def equip(item):
x = True
while x == True:
if len(bag_sword) > 1:
print "You can't have 2 weapons equipped!"
break
if len(bag_chest) > 1:
print "You can't have 2 chestplates equipped!"
break
if len(bag_gloves) > 1:
print "You can't have 4 gloves equipped!"
break
if len(bag_helmet) > 1:
print "You can't have 2 helmets equipped!"
break

if item == "iron sword" and "iron sword" in bag:
print "\nYou equip the Iron Sword"
bag.remove("iron sword")
bag_sword.append("iron sword")
break


Whenever I run this function a second time after I put "iron sword" into one of the
bag_
s, and try to add another to test it, it doesn't do anything and the code completely freezes.

The
bag_
s are all lists.

My guess was the while loop was stuck and it wasn't changing the length whenever I put something into the list in-game, because that's not how the language works?

Answer

Once you added a sword to the bag, none of your conditions are true. Your len(bag_sword) is exactly 1, (so if len(bag_sword) > 1: won't be matched), and 'iron sword' in bag is false.

Because none of your if statements match, no break is executed and your while loop goes on forever.

You don't want to test if there is more than one item in your bag_sword. Test if there is any item in that bag:

if bag_sword:  # true if not empty
    print "You can't have 2 weapons equipped!"
    break

because you are testing before adding a second weapon.

Comments