2014-03-03 98 views
-1
import random 

hp = 100 
eh = 100 



while hp > 0 and eh > 0: 

    print("Action? (attack, heal, nothing):") 

    act = input(">") 

    attack = random.randint(1, 30) 

    heal = random.randint(1, 15) 




if act == "attack" or "Attack": 
    eh = eh - attack 
    print(attack) 
    print("eh = %s" % eh) 

elif act == "heal" or "Heal": 
    hp = hp + heal 
    print("You have healed %s points" % heal) 
    print(hp) 

爲什麼當我輸入heal時,它也會運行攻擊部分呢?即使我輸入既沒有攻擊也沒有治療,它仍然會運行攻擊部分。請幫我用我的代碼(Python)

+1

遇見一個有用的[方法](http://docs.python.org/2/library/stdtypes.html#str.lower):'如果行爲。lower()==「attack」:' – dawg

回答

1

您使用or是錯誤的。它的行爲如同你有:

if (act == "attack") or ("Attack"): 

任何非空字符串評估爲True

而是使用:

if act == "attack" or act == "Attack": 

甚至:

if act in ("attack", "Attack"): 
0

在這種條件:後

if act == "attack" or "Attack": 

的部分或結果始終爲true。

>>> if "Attack": 
...  print "Yup." 
... 
Yup. 

你大概的意思是

if act == "attack" or act == "Attack": 
    eh = eh - attack 
    print(attack) 
    print("eh = %s" % eh) 

elif act == "heal" or act == "Heal": 
    hp = hp + heal 
    print("You have healed %s points" % heal) 
    print(hp) 

雖然一個更好的辦法是

if act.lower() == "attack": 
0

首先,我假設,如果和elif的部分縮進以適應while循環。

它開火攻擊部分的所有時間背後的原因,是你的條件:

if act == "attack" or "Attack": 

它基本上等於

if (act == "attack") or ("Attack"): 

這意味着相同

if (act == "attack") or (True): 

所以其實際上總是如此。

要使其工作之前,你應該重複「行爲==」部分「攻擊太」這個消息是絕對

if act == "attack" or act == "Attack": 
    eh = eh - attack 
    print(attack) 
    print("eh = %s" % eh) 

elif act == "heal" or act == "Heal": 
    hp = hp + heal 
    print("You have healed %s points" % heal) 
    print(hp) 
0

除非我記錯了,我覺得你的if語句應該是

if act == "attack" or act=="Attack": 

正因爲如此,

if "Attack" 

將始終評估爲真,那麼攻擊部分將始終運行。

我也可以推薦這樣做

act.toLower() == "attack" 

這樣你可以做一個比較,而忽略大小寫。只是一個想法。

+0

它只是'.lower()'在Python中不是'.toLower()' – dawg