为什么两个不同的数字在元组中返回相同的字符串?

时间:2014-05-27 16:41:58

标签: python text tuples

我是Python编码的新手,而且我一直在制作简短的游戏,以便更加流利地编写代码。我现在有一个"模拟"这实际上是一个英雄和妖精之间的基于文本的斗争。我使用一个元组来存储移动列表,然后在一系列if语句中调用该元组中的元素。我的问题是,当用户输入数字2时,"药水"使用移动,但当用户输入3时,"药水"移动也被使用。数字2应该触发"块"移动,但没有。我认为这可能与我对元组的有限知识有关,但有人可以为我澄清这一点吗?非常感激。代码如下......

#begins battle loop
while goblin > 0:

    hmoves = ('sword',
             'shield bash',
             'block',
             'potion')

    choice = int(input("\nEnter a number 0 - 3 to choose an attack: "))

    if hmoves[choice] is 'sword':
        print(name, "attacked with his sword!")
        goblin -= 3
        print("\ngoblin used bite!")
        hero -= 2
        print("Goblin HP:", goblin, "Hero HP:", hero)
    elif hmoves[choice] is 'shield bash':
        print(name, "used shield bash!")
        goblin -= 2
        print("\ngoblin used bite!")
        hero -= 2
        print("\nGoblin HP:", goblin, "Hero HP:", hero)
    elif hmoves[choice] is 'block':
        print(name, "used block!")
        print("\ngoblin used bite!")
        print("but it was blocked.")
        hero = hero
        goblin = goblin
        print("\nGoblin HP:", goblin, "Hero HP:", hero)
    elif hmoves[choice] is 'potion':
        print(name, "used a health potion.")
        hero += 4
        print("\ngoblin used bite!")
        hero -= 2
        print("\nGoblin HP:", goblin, "Hero HP:", hero)

    #print("Goblin HP:", goblin, "Hero HP:", hero)

if goblin <= 0:
    print("Congratulations you've completed the simulation.")
else:
    print("Sorry, you did not pass the simulation.")

1 个答案:

答案 0 :(得分:2)

您应该将您的资料从is更改为==

goblin = 20
hero = 20
name = "lol"

#begins battle loop
while goblin > 0:

    hmoves = ('sword',
             'shield bash',
             'block',
             'potion')

    choice = int(input("\nEnter a number 0 - 3 to choose an attack: "))

    if hmoves[choice] == 'sword':
        print(name, "attacked with his sword!")
        goblin -= 3
        print("\ngoblin used bite!")
        hero -= 2
        print("Goblin HP:", goblin, "Hero HP:", hero)
    elif hmoves[choice] == 'shield bash':
        print(name, "used shield bash!")
        goblin -= 2
        print("\ngoblin used bite!")
        hero -= 2
        print("\nGoblin HP:", goblin, "Hero HP:", hero)
    elif hmoves[choice] == 'block':
        print(name, "used block!")
        print("\ngoblin used bite!")
        print("but it was blocked.")
        hero = hero
        goblin = goblin
        print("\nGoblin HP:", goblin, "Hero HP:", hero)
    elif hmoves[choice] == 'potion':
        print(name, "used a health potion.")
        hero += 4
        print("\ngoblin used bite!")
        hero -= 2
        print("\nGoblin HP:", goblin, "Hero HP:", hero)

Refer to the difference between is and ==.这两个字符串不一定是内存中的同一个对象,但它们在字符方面是相同的。它有时会起作用,因为string interning用于提高效率。