Python一直在说NameError:名称'name'未定义

时间:2014-01-04 17:34:53

标签: python

def main():
    name = raw_input("What is your name?")
    age = raw_input("How old are you?")
    color = raw_input("What is your favorite color?")

print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, age, color)
if __name__ == '__main__':
    main()

我正在尝试从Codeacademy复制以下代码:

name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")

print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)

3 个答案:

答案 0 :(得分:3)

打印应该在main函数的范围内,以便访问其变量:

def main():
    name = raw_input("What is your name?")
    age = raw_input("How old are you?")
    color = raw_input("What is your favorite color?")

    print "Ah, so your name is %s, your quest is %s, " \
    "and your favorite color is %s." % (name, age, color)

if __name__ == '__main__':
    main()

应该这样做。

答案 1 :(得分:1)

nameagecolor都是main的本地人。因此,您无法在函数外部访问它们。

我认为这里最好的解决方案是缩进print第一行:

def main():
    name = raw_input("What is your name?")
    age = raw_input("How old are you?")
    color = raw_input("What is your favorite color?")

    print "Ah, so your name is %s, your quest is %s, " \
        "and your favorite color is %s." % (name, age, color)
if __name__ == '__main__':
    main()

现在,它与nameagecolor的范围相同,可以很好地访问它们。

答案 2 :(得分:0)

您设置name的唯一时间是您调用main功能时。在之后调用main函数的唯一时间是,因为print语句不是print的一部分。因此,名称未定义。

如果您打算复制codeacademy代码,则需要调整print语句的缩进,使其与main语句处于同一级别。这是因为python使用缩进量来知道一行代码所属的块。您希望print语句与输入语句位于同一个块中。

例如:

raw_input