首页 > 解决方案 > 当我尝试创建多个分支时,它不断给我一个名称错误

问题描述

我正在尝试创建几个分支,这一直给我这个名称错误

我尝试删除它给我的问题,然后我想我正在删除整个东西

while True:
    d1a = input ("Do you want to: A) Approach the house. B) Approach the stable. [A/B]? : ")
    # check if d1a is equal to one of the strings, specified in the list
    if d1a in ['A', 'B']:
        # if it was equal - break from the while loop
        break
if d1a == "A": 
    print ("You approach the cottage.") 
elif d1a == "B": 
    print ("You approach the stables.")

错误:回溯(最近一次调用最后一次):文件“main.py”,第 5 行,在 d1a = 输入(“你想:A)接近房子。B)接近马厩。[A/B]?: “)文件“”,第 1 行,在 NameError 中:名称 'A' 未定义

标签: python

解决方案


看来您正在运行 Python 2,也称为旧版 Python。在那个版本的 Python 中,input尝试评估输入。你输入A,所以 Python 试图找到它的值。没有命名变量A,因此您收到错误消息。

使用raw_input而不是input. 或者更好的是,转到 Python 3。您的代码在我的 Python 3.7.3 中运行良好。


推荐阅读