简体   繁体   中英

Python - how to define a variable using a function?

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM