Python 到目前为止,我的代码有两个问题。

Python 到目前为止,我的代码有两个问题。,python,loops,while-loop,Python,Loops,While Loop,因此,由于某些原因,当给出的响应不是Start或Start或Begin或Begin时,代码不会输入有效的响应。我希望它能循环回到userinput阶段,但它只是在程序中继续运行,就好像一切正常一样。我不知道我在哪里搞砸了 其次,我希望当生命值下降到0以下时,opponentHp自动等于0。例如,当opponentHp=-45时,opponentHp应该等于0 非常感谢您的帮助。如果条款有误,请说明条件。您应该为每个或重复“userInput==”。 或者,更简洁地说: from random i

因此,由于某些原因,当给出的响应不是Start或Start或Begin或Begin时,代码不会输入有效的响应。我希望它能循环回到userinput阶段,但它只是在程序中继续运行,就好像一切正常一样。我不知道我在哪里搞砸了

其次,我希望当生命值下降到0以下时,opponentHp自动等于0。例如,当opponentHp=-45时,opponentHp应该等于0


非常感谢您的帮助。

如果条款有误,请说明条件。您应该为每个或重复“userInput==”。 或者,更简洁地说:

from random import randint
from time import sleep

fight = False

def start_up():
    print("Fight Simulator - Test Stages.")
    userInput = str(input("Enter your name "))
    user_name = userInput
    return user_name

def intro():
    userName = start_up()
    while True:
        userInput = str(input("Welcome to the dojo, {}. To commence the first battle, type 'Start', or 'Begin'".format(userName)))
        if userInput == "Start" or "start" or "Begin" or "begin":
            return userInput
        else:
            print("Enter a valid response")
            break

def fight_commence():
    userInput = intro()

    if userInput == "Start" or "start" or "Begin" or "begin":
        fight = True

        userHp = 100
        opponentHp = 100

        while fight == True:
            userDmg = randint(0,100)
            opponentDmg = randint(0,100)

            opponentHp -= userDmg

            if opponentHp <= 0:
                opponentHp == 0

            print("You did {} damage".format(userDmg))
            sleep(1)
            print("Opponent has {} hp remaining".format(opponentHp))
            sleep(1)

            if opponentHp <= 0:
                print("You killed him!")
                fight = False
    else:
        print("Enter a valid action")

fight_commence()

“有效输入”测试的一个大问题是测试的方式

userInput.lower() in ["start", "begin"]
这不是有效的python条件。相反,你可以这样做:

if userInput == "Start" or "start" or "Begin" or "begin"
这种比较会发生两次,而且是不好的。对于opponenthp为0,您当前将此作为您的声明和结果:

if userInput in ["Start", "start", "Begin", "begin"]
加成
此外,除了上述项目之外,当使用断言语句时,您将结束无限循环,并且设置了没有返回值的函数,您可能需要考虑将其更改为“继续”或“传递”语句,或者干脆删除它。

如果您标记语言,可能会有所帮助……到目前为止,我的代码有两个问题不是一个非常具体/可搜索的标题。你的问题很典型:如果userInput==Start或Start或Begin或Begin:没有做你认为应该做的事情。。。提示:把它当作userInput==Start或Start或Begin或Begin或Begin来阅读:这可能是一个经过一些编辑的好问题,但就目前而言,我投了反对票。
if opponentHp <= 0:
    opponentHp == 0
if opponentHp <= 0:
    opponentHp = 0