用户输入未存储在variab中

2024-06-23 19:31:22 发布

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

我是一个新的计算机老师,我对这段代码有一些问题。我试图让我的学生用while和if语句创建一个非常简单的游戏。你知道吗

当我运行这个代码时,它不会接受我输入的y或n,它会不断出现错误。知道为什么吗?你知道吗

monsterHealth = 20
playerHealth = 50

while monsterHealth > 0:
    print ("The monster attacks you dealing 10 damage")
    global playerHealth
    playerHealth = playerHealth - 10

    playerDecision = input("Would you like to stay and fight? y/n")

    if playerDecision == y:
        print ("You attack the monster and do 5 damage")
    if playerDecision == n:
        print("You run away with your tail between your legs.")
        break


    if playerHealth <= 0:
        print ("You died......")
        break
    if monsterHealth <= 0:
        print ("You defeated the monster!")
        break

Tags: andthe代码youyourifprintbreak
3条回答

由于未定义变量y,因此得到的错误是NameError。 你真正想做的是

if playerDecision == 'y':
    print ("You attack the monster and do 5 damage")
if playerDecision == 'n':
playerDecision = input("Would you like to stay and fight? y/n")

if playerDecision == 'y':  # <  this should fix it. 
    print ("You attack the monster and do 5 damage")
if playerDecision == 'n':
    print("You run away with your tail between your legs.")
    break     

if playerHealth <= 0:
    print ("You died......")
    break   

if monsterHealth <= 0:
    print ("You defeated the monster!")
    break   

您将playerDecision变量y变量n进行比较。你知道吗

您应该将其更改为字符串"y""n"

if playerDecision == "y":
if playerDecision == "n":

相关问题 更多 >

    热门问题