如果/ elif语句只给我一个答案

时间:2016-03-26 13:42:07

标签: python python-3.x if-statement

这是我的Python RPG游戏中的商店代码。无论我选择什么值,代码都会执行以下内容:如果我输入了匕首。它也从未告诉我,我的资金不足。总是一样的答案

global gcredits
dagger = Item('Iron dagger', 5, 5)
sword = Item('Iron sword', 10, 12)
armour = Item('Iron Armour', 15, 20)


print ("Welcome to the shop! Buy all your amour and weapon needs here!")
print ("You have",gcredits,"Galactic Credits!")

print (dagger.name,': Cost:', dagger.value,'Attack points:', dagger.hvalue)
print (sword.name,': Cost:', sword.value,'Attack points:', sword.hvalue)
print (armour.name,': Cost:', armour.value,'Attack points:', armour.hvalue)

choice = input('What would you like to buy?').upper()

if choice == 'DAGGER' or 'IRON DAGGER' or 'IRONDAGGER':
    print ("You have selected the Iron Dagger.")
    if gcredits >= 5:
        print ('Purchase successful')
        gcredits = gcredits - 5

        dEquip = True
        shop()
    elif gcredits < 5:
        print ("You have got insufficient funds")
        shop()

elif choice == 'SWORD' or 'IRON SWORD' or 'IRONSWORD':
    if gcredits >= 10:
        print ('Purchase successful')
        gcredits = gcredits - 10

        sEquip = True
        shop()
    elif gcredits < 10:
        print ("You have got insufficient funds")
        shop()

elif choice == 'ARMOUR' or 'IRON ARMOUR' or 'IRONARMOUR':
    if gcredits >= 15:
        print ('Purchase successful')
        gcredits = gcredits - 15

        aEquip = True
        shop()
    elif gcredits < 15:
        print ("You have got insufficient funds")
        shop()

else:
    print ("That is not an item. Try again.")
    shop()

1 个答案:

答案 0 :(得分:1)

您编写OR条件的方式是错误的:

if choice == 'DAGGER' or 'IRON DAGGER' or 'IRONDAGGER':

应该是:

if choice == 'DAGGER' or choice == 'IRON DAGGER' or choice == 'IRONDAGGER':

或更多Python:

if choice in ('DAGGER', 'IRON DAGGER', 'IRONDAGGER'):

执行if choice == 'DAGGER' or 'IRON DAGGER'时发生的事情是检查是否

  1. 您的choice DAGGERTrue
  2. 您的choice IRON DAGGERTrue
  3. 但你检查是否

    1. 您的choice DAGGERTrue
    2. 如果IRON DAGGERTrue
    3. 请注意,if 'IRON DAGGER'将始终返回True

      if 'IRON DAGGER': #this is always true