0

I have a function that returns a number. I want to assign a variable to have this value, but python gives a runtime error when I say temp = foo(i, j) : NameError: name 'foo' is not defined. Note that I've changed the function bodies of bar and foo around, obviously having a function that just returns 1 is useless, but it doesn't change my error.

sum = 0
for i in range(2, 100):
    for j in range(2, i):
        temp = foo(i, j)
        if (temp > 100):
            sum = sum + 1
print sum

def bar (n, a):
    r = 1
    return r

def foo (n, a):
    s = bar(n, a)/factorial(5);
    return s

def factorial (n):
    r = 1
    for i in range (2, n + 1):
        r *= i;
    return r

3 Answers 3

3

Names in Python do not exist until they are bound. Move the def foo(...): block above the code that uses foo().

Sign up to request clarification or add additional context in comments.

Comments

3

Your definition of foo is AFTER you use it in the file. Put your function definition above the for loop.

Comments

2

As per other answers, your issue is the order in which you run your code: foo hasn't been defined yet when you first call it. Just wanted to add a comment about best practices here.

I always try to put everything in a function and then call any scripts at the bottom. You've probably encountered this pattern before, and it's a good habit to get into:

CONSTANT = 5

def run():
    for i in xrange(CONSTANT):
        print foo(i)   # whatever code you want

def foo(n):
    # some method here...
    pass

if __name__ == "__main__":
    run()

if you run this with python script.py or by hitting f5 in idle, run() will be executed after everything is defined.

By following this pattern you don't have to worry about the order you define your functions in, and you get the added benefit of being able to import foo with other functions without having your script execute during the import, which is probably not a desired behavior.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.