[英]Why is it that two different numbers return the same string in a tuple?
我是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.")
您應該將東西從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)
請參閱is和==之間的區別。 這兩個字符串在內存中不一定是相同的對象,但是就字符而言它們是相同的。 盡管有時由於有效的字符串interning ,它仍然可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.