0

I'm calling a function outside main, like below, and running into name error. Is there a way to resolve this error without moving the function call getdata() inside main?

filename="data_file.txt"
AU=getdata(filename)

def getdata(filename):
    file = open(filename,'r')
    return file.read()

def main():

NameError: name 'getdata' is not defined
1
  • 2
    You need to put a pass under main(), by the way; can't just leave it empty.
    – jdotjdot
    Dec 27, 2012 at 23:01

2 Answers 2

3

You don't need to use a main() function at all; happens though that, in your code, the definition of getdata() has not been reached before the function call.

Try the following:

def getdata(filename):
    file = open(filename,'r')
    return file.read()

filename="data_file.txt"
AU=getdata(filename)
3

You can only call a function after it is defined. Move the AU line after defining getdata():

def getdata(filename):
    file = open(filename,'r')
    return file.read()

AU = getdata(filename)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.