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)
答案 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)
name
,age
和color
都是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()
现在,它与name
,age
和color
的范围相同,可以很好地访问它们。
答案 2 :(得分:0)
您设置name
的唯一时间是您调用main
功能时。在之后调用main
函数的唯一时间是,因为print语句不是print
的一部分。因此,名称未定义。
如果您打算复制codeacademy代码,则需要调整print语句的缩进,使其与main
语句处于同一级别。这是因为python使用缩进量来知道一行代码所属的块。您希望print语句与输入语句位于同一个块中。
例如:
raw_input