请帮我处理我的代码(Python)

时间:2014-03-03 00:46:45

标签: python python-3.x

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)

为什么当我输入痊愈时,它也会运行攻击部分?即使我既没有攻击也没有治疗,它仍会运行攻击部分。

4 个答案:

答案 0 :(得分:1)

您对or的使用不正确。它的表现就好像你有:

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

任何非空字符串的计算结果为True

改为使用:

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

甚至:

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

答案 1 :(得分:0)

在此条件中:

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

之后的部分或总是评估为真。

>>> 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":

答案 2 :(得分:0)

首先,我假设if和elif部分缩进以适应while循环。

它一直触发攻击部分背后的原因,是你的条件:

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

它基本上等于

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

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

所以它实际上总是如此。

为了使它工作,你应该在“攻击太”之前重复“act ==”部分,所以它是

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)

答案 3 :(得分:0)

除非我弄错了,否则我认为你的if语句应该是

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

实际上,

if "Attack" 

将始终评估为true,因此攻击部分将始终运行。

我可能也建议你做

act.toLower() == "attack"

这样您就可以进行单一比较并忽略区分大小写。只是一个想法。