我的elif陈述有问题

时间:2017-06-17 16:19:06

标签: python python-3.x

我正在编写游戏以尝试提高我在python中的技能。在这部分代码中,我试图用金钱系统对一个商店进行编程,测试一个变量对5个不同的可能答案

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()

当您输入health potion时,代码会像正常情况一样继续,但是其他输入会转到代码的这一部分

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()

2 个答案:

答案 0 :(得分:0)

为了好玩,这是一个更高级的版本。

如果一切都没有意义,请不要担心;尝试追踪它并弄清楚它是如何工作的。一旦你完全理解它,你将更好地掌握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()

答案 1 :(得分:-2)

您的问题在于此声明:

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

比较像这样的字符串不起作用。您需要确保它不在字符串数组中

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

否则它将永远为真,因此第一个语句将始终执行。

相关问题