请帮助我编写代码(Python)

2024-04-20 06:18:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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时,它也会运行攻击部分?即使我既不攻击也不治疗它仍然运行攻击部分。你知道吗


Tags: orandimportinputactionrandomacthp
3条回答

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

它一直发射攻击部分的原因是你的状况:

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

基本上等于

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

意思和

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

所以事实上总是这样。你知道吗

为了让它工作,你应该重复“act==”部分在“Attack too”之前,所以它是

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 == "attack" or "Attack":

or后面的部分总是求值为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":

你使用or是不正确的。就像你有:

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

任何非空字符串的计算结果都是True。你知道吗

而是使用:

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

甚至:

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

相关问题 更多 >