我尝试编写程序但遇到了return语句的问题。
以下代码行引发了一条错误消息,指出变量names
未定义。
但是,我确实使用return语句返回names
并将其传递给main函数:
def main(names):
names_in()
print(names)
# import the record, put it into a list, pass that list to main().
def names_in():
infile = open('names.txt','r')
names = infile.readlines()
infile.close()
index = 0
while index < len(names):
names[index] = names[index].rstrip('\n')
index += 1
return names
main(names)
我之前写过另一个程序也做了同样的事情,一切正常,所以我不确定这里有什么问题?
答案 0 :(得分:5)
你的问题在这里:
main(names)
您正在使用尚未定义的变量名称调用main
函数。您得到的错误应显示指向此行的行号:这将验证问题所在。
# 'names' is not defined in this scope
def main(names):
# Some code
# 'names' is a variable that is 'in scope' here because it's passed as an 'argument'
# 'names' is not defined in this scope either
# import the record, put it into a list, pass that list to main().
def names_in():
infile = open('names.txt','r')
names = infile.readlines() # defines 'names' for this scope
# more code
return names # because 'names' is defined it can return it
# 'names' is no longer defined in this scope
main(names) # This fails because when the compiler tries to resolve 'names' it can't find anything
根据您显然要做的事情,您需要修改main
功能,如下所示:
def main():
print(names_in())
并称之为:
main()
请注意,您似乎对如何执行代码感到困惑。如果我写:
def a():
print("a")
def b():
print("b")
print("c")
b()
a()
它被翻译成等同于:
的东西print("c")
print("b")
print("a")
将def
语句有效地复制粘贴到调用它们的位置。
答案 1 :(得分:1)
您的main
函数不应包含任何参数。相反,它应该使用names_in
的返回值:
def main():
names = names_in()
print(names)
稍后在您的代码中:
main()