<p>我是一个新的计算机老师,我对这段代码有一些问题。我试图让我的学生用while和if语句创建一个非常简单的游戏。你知道吗</p>
<p>当我运行这个代码时,它不会接受我输入的y或n,它会不断出现错误。知道为什么吗?你知道吗</p>
<pre><code>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
</code></pre>
<p>由于未定义变量y,因此得到的错误是NameError。
你真正想做的是</p>
<pre><code>if playerDecision == 'y':
print ("You attack the monster and do 5 damage")
if playerDecision == 'n':
</code></pre>