0

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?

3
  • 2
    n is not global inside of check() - you'd need to put the global n there, the one in main() isn't actually accomplishing anything since nothing outside of main is accessing it. Commented May 27, 2017 at 1:38
  • 1
    btw, I'm not sure there is something recursive there as the title suggests. Commented May 27, 2017 at 1:43
  • There's also no apparent reason for defining check at all, let alone inside main. Commented May 27, 2017 at 2:08

1 Answer 1

3

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 thatn 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.

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

4 Comments

Furthermore, you don't need the global keyword in the first n declaration, you can just do n = 1. This is because global just prevents a local variable from being created on assignment in the inner scope when there's a global with the same name.
@PedrovonHertwig I didn't know what the OP want, just followed his original code. Maybe he did want the n to be global.
Your answer is correct, I'm just adding an explanation and pointing out that unless n is defined in top-level scope, the first global n statement has no effect.
@PedrovonHertwig Thank you for your further explanation, I added some text regarding that topic:)

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.