简体   繁体   中英

Python Global Variables for Recursive Function

In my math class, we have been told to write a program in python. In one of the parts, I want to test the convergence of a series. While writing the program, I realized I was fundamentally misunderstanding something about how python handles global variables. Take this code:

def main():

    global n
    n = 1

    def check():

        a = 10
        if n > a: print(n)
        else: n += 1

    check()

main()

This code fails because it says that n has not been defined yet. However, I can't define n inside of the check() function since that would just reset n to one upon every iteration! Is there some workaround for this problem?

As already stated in the comments, n isn't in the global scope yet, since it's inside the nested function check . You will need to add global n to the check 's scope, to access the global n value from the nested function:

def main():   
    global n
    n = 1

    def check():
        global n
        a = 10
        if n > a: print(n)
        else: n += 1

    check() 
main()

@PedrovonHertwig also pointed out you don't need global n in main (which is the case in your current context, ignore this if you want to use n elsewhere in the top-level scope) and that n is perfectly fine staying in main 's local scope. You can then replace the global keyword inside check to nonlocal n , telling python to use the n that is not in the local scope nor the global scope, but main 's scope.

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