I tried to code a program but ran into problem with the return statement.
The following lines of code raised an error message saying that the variable names is undefined.
However, I did use the return statement to return names and pass it to the main function:
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)
I've written another program before that did the same thing and everything worked fine, so I'm not sure what's wrong here?
def main(names):? Does it really need an argument here? And maybe you meanprint(names_in()).names_inmakes me cringe. It could simplify to:with open('names.txt', 'r') as infile: return [name.rstrip('\n') for name in infile]and would run faster, as well as more obviously and idiomatically.closeinstead of allowingwithto do the work reliably/safely). Literally the whole function could be rewritten as two idiomatic lines.