我在尝试编写此代码时有疑问。它显示“ NameError:第1行未定义名称'answer'”的错误。有人可以指出出什么问题了吗?
def main():
answer = input("Would you like to play a game? yes or no")
if (answer == "yes"):
firstChoice = input(
"There was once a knight, stuck in a forest trying to look for a princess. The knight had 2 ways he could go. Should he go left, or right?"
)
if (answer == "left"):
secondChoice = input(
"He decides to go left. As he passes the trees, he sees something he hasn’t seen before. A GIANT DRAGON! He pulls out one of his weapons. Which weapon did he pull out? Oversized Sword or Flamethrower?"
)
if (answer == "mighty sword"):
thirdChoice = input("He pulls out his mighty weapon. It was about as tall as a bus! The dragon said, Wait, just the size of a bus? I’m like, 200 buses. The knight, realizing that his choice was stupid, got the heck out of there! The dragon, being the 200 buses that he is, couldn’t find the puny mortal. He decided to brush it off and went to his dome. The poor knight, out of breath, gets a drink of water from a creek. The knight says, Wait, I know this creek! This is the Golden Creek, so if I follow this path, the dome should be right there! The knight decides to go with his gut and follow the path. And before he knows it, the princess was trapped inside of the dragon’s dome! He knew he had to do something, but what? Should he sneak in, or barge in alone?")
if (answer == "sneak in"):
print("He tries to sneak in. Getting past every dragon guard, was surprisingly easy. Their eyes are on the side of their head, so if you just walk in front of them, you should be good. Luckily, when the knight came, the dragon was asleep. He needed crucial silence, where not the single creek of wood, or cling of the armor could wake up the dragon. The knight whispers to the princess, I have come to save you! The princess carefully follows the brave knight, and they make it out! The king is happy with your success in keeping the princess alive, and you are promoted to secretary, the highest rank below the king! YOU WIN")
答案 0 :(得分:2)
首先,您不需要在if
语句中使用括号。该错误可能是由于在定义函数时未使用选项卡引起的。
很抱歉建议使用IDE,不知道如何复制和粘贴文本...
答案 1 :(得分:2)
这是范围错误。您可以在主要方法中初始化答案,但是一旦该方法关闭,该变量就会被删除。 3个if语句无权访问此变量。
答案 2 :(得分:1)
没有运行您的代码,我会看到一个大问题,您可能想尝试一下
在每个输入标签之后,您说“ if answer ==“ 但是请记住,答案变量将是用户输入的第一件事
因此,如果他们将“ yes”设为“ yes”,那么在整个脚本中答案变量始终为“ yes”,除非您重新定义
编辑 当我第一次回答时,帖子并不完全在代码块中,所以我看不到缩进
答案 3 :(得分:0)
变量answer
仅在main()
内,才能在main()
之外使用它,您应该全局定义它,这意味着在主函数之前
答案 4 :(得分:0)
实际上,您只需要在声明前使用 global
。