我尝试编写一个程序,但遇到了 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)
我之前写过另一个程序做同样的事情并且一切正常,所以我不确定这里出了什么问题?
请您参考如下方法:
你的问题在这里:
main(names)
您正在使用尚 undefined variable 名称调用您的 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 语句被有效地复制粘贴到它们被调用的地方。
