-3

I'm programming a game to try and improve my skills in python. In this part of the code I am trying to program a shop with a money system testing one variable against 5 different possible answers

while True:
                choice=str(input("What would you like to buy? (Type in 'nothing' when you don't want anymore items)  "))
                if choice!="health potion" and "strength potion" and "strength booster" and "armour piece" and "nothing":
                    print()
                    next_line=input("I do not understand what you wrote. Try again please ")
                    print()
                elif choice=="nothing":
                    next_line=input("The merchant says 'Thanks for business' ")
                    print()
                    break
                elif choice=="health potion":
                    gold=gold-10
                    if gold<0:
                        gold=gold+10
                        next_line=input("Sorry but you don't have enough gold ")
                        print()
                    else:
                        next_line=input("You bought a health potion ")
                        health_potions=health_potions+1
                        next_line=input("You now have "+str(gold)+" gold coins ")
                        print()
                elif choice=="strength potion":
                    gold=gold-15
                    if gold<0:
                        gold=gold+15
                        next_line=input("Sorry but you don't have enough gold ")
                        print()
                    else:
                        next_line=input("You bought a strength potion ")
                        strength_potions=strength_potions+1
                        next_line=input("You now have "+str(gold)+" gold coins ")
                        print()
                elif choice=="strength booster":
                    gold=gold-45
                    if gold<0:
                        gold=gold+45
                        next_line=input("Sorry but you don't have enough gold ")
                        print()
                    else:
                        next_line=input("You boosted your strength ")
                        strength_booster=strength_booster+1
                        next_line=input("You now have "+str(gold)+" gold coins ")
                        print()
                elif choice=="armour piece":
                    gold=gold-30
                    if gold<0:
                        gold=gold+30
                        next_line=input("Sorry but you don't have enough gold ")
                        print()
                    else:
                        next_line=input("You bought an armour piece ")
                        armour=armour+1
                        next_line=input("You now have "+str(gold)+" gold coins ")
                        print()

When you input health potion the code goes on like normal but with the other inputs it goes to this part of the code

if choice!="health potion" and "strength potion" and "strength booster" and "armour piece" and "nothing":
                print()
                next_line=input("I do not understand what you wrote. Try again please ")
                print()
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ricardo
  • 1
  • 3
  • 4
    Possible duplicate of [How do I test one variable against multiple values?](https://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – jonrsharpe Jun 17 '17 at 16:22
  • That question is multiple variables for multiple values not one variable like in my code @jonrsharpe – Ricardo Jun 17 '17 at 16:38
  • Change your third line to `if choice in ("health potion", "strength potion", "strength booster", "armour piece", "nothing"'):` – Rory Daulton Jun 17 '17 at 16:38
  • That's irrelevant, it doesn't matter what you're comparing to what. – jonrsharpe Jun 17 '17 at 16:39

2 Answers2

0

For fun, here is a significantly more advanced version.

Don't worry if it doesn't all make sense right away; try tracing through it and figuring out how it works. Once you fully understand it you will have a much better grasp of Python!

class Character:
    def __init__(self, name, health=50, strength=20, gold=200, inventory=None):
        """
        Create a new character

        inventory is a list of items (may have repeats)
        """
        self.name = name
        self.health = health
        self.strength = strength
        self.gold = gold
        self.inventory = [] if inventory is None else list(inventory)

    def buy(self, item):
        """
        Buy an item
        """
        if self.gold >= item.cost:
            print(item.buy_response.format(name=item.name, cost=item.cost))    # print acceptance
            self.gold -= item.cost                                             # pay gold
            item.buy_action(self)                                              # apply purchased item to character
            return True
        else:
            print("Sorry but you don't have enough gold.")
            return False

class Item:
    def __init__(self, name, cost, buy_response="You bought a {name} for {cost} GP", buy_action=None):
        # store values
        self.name = name
        self.cost = cost
        # what to print on a successful purchase
        self.buy_response = buy_response
        # apply a purchased item to the character
        self.buy_action = self.make_buy_action() if buy_action is None else buy_action

    def make_buy_action(self):
        def buy_action(char):
            """
            Purchase default action: add item to character inventory
            """
            char.inventory.append(self)
        return buy_action

    @staticmethod
    def buy_strength_booster(char):
        """
        Purchase strength booster action: increase character strength
        """
        char.strength += 1

    def __str__(self):
        return self.name

class Shop:
    def __init__(self, name, *inventory):
        """
        Create a shop

        inventory is a list of (num, item); if num is None the store has an unlimited supply
        """
        self.name = name
        self.inventory = {item.name:(num, item) for num,item in inventory}

    def visit(self, char):
        """
        Serve a customer
        """
        print("\nHowdy, {}, and welcome to {}!".format(char.name, self.name))

        while True:
            print("\nWhat would you like to buy today? (type 'list' to see what's available or 'done' to leave)")
            opt = input("{} GP> ".format(char.gold)).strip().lower()
            if opt == 'done':
                print("Have a great day, and c'mon back when you've got more gold!")
                break
            elif opt == 'list':
                item_names = sorted(name for name, (num, item) in self.inventory.items() if num is None or num > 0)
                if item_names:
                    print(", ".join(item_names))
                else:
                    print("Huh - looks like we're all sold out. Try again next week!")
                    break
            elif opt in self.inventory:
                num, item = self.inventory[opt]
                if num is None or num > 0:
                    yn = input("That's {} GP. You want it? [Y/n]".format(item.cost)).strip().lower()
                    if yn in {'', 'y', 'yes'}:
                        if char.buy(item) and num is not None:
                            self.inventory[opt] = (num - 1, item)
                    else:
                        print("(scowling, the proprietor stuffs the {} back under the counter)".format(item.name))
                else:
                    print("'Fraid we're all out of those.")
            else:
                print("Sorry, hain't had one o' those around in a coon's age!")

def main():
    # stock the store
    shop = Shop("Dwarven Dave's Delving Deal Depot",
        (6,    Item("health potion",    10)),
        (6,    Item("strength potion",  15)),
        (3,    Item("strength booster", 45, "You boosted your strength!", Item.buy_strength_booster)),
        (None, Item("armor piece",      30))   # unlimited stock
    )

    # create a buyer
    jeff = Character("Jeff")

    # visit the store
    shop.visit(jeff)

if __name__ == "__main__":
    main()
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • Could you explain what each bit of the code is and how it works because I'm very new to this and don't have much experience with it? @Hugh Bothwell – Ricardo Jun 30 '17 at 17:36
-2

Your issue is with this statement:

if choice!="health potion" and "strength potion" and "strength booster" and "armour piece" and "nothing":

Comparing strings like this doesn't work. You need to make sure it isn't in an array of the strings

if choice not in ("health potion","strength potion","strength booster","armour piece","nothing"):

Otherwise it will always be true, so the first statement will always execute.

dwmyfriend
  • 224
  • 1
  • 10