Minh Le
Minh Le

Reputation: 29

return statement in python

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?

Upvotes: 1

Views: 148

Answers (2)

Nathaniel Ford
Nathaniel Ford

Reputation: 21220

Your problem is here:

main(names)

You are calling your main function with a variable name that hasn't been defined yet. The error you're getting should display a line number that points to this line: that will validate this is where the problem is.

# '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

Based on what you're apparently trying to do, you need to modify your main function like so:

def main():
    print(names_in())

And call it like so:

main()

Note, too, you seem to have some confusion over how code is executed. If I write:

def a():
    print("a")

def b():
    print("b")

print("c")
b()
a()

It gets translated to something equivalent to:

print("c")
print("b")
print("a")

The def statements get copy-pasted, effectively, into where they are called.

Upvotes: 5

Hai Vu
Hai Vu

Reputation: 40723

Your main function should not take in any parameter. Instead, it should use the return value from names_in:

def main():
    names = names_in()
    print(names)

Later in your code:

main()

Upvotes: 1

Related Questions