0
def a():
    x=20
    def b():
        global x
        x=88
        print("before calling b",x)
        b()
        print("after calling b",x) 
a()

My code is showing no error while debugging but when I run it, it shows no output. It is not getting the function.

2
  • 2
    you don't want to call b()? Commented Jun 7, 2020 at 15:48
  • Is the code you see in the post indentend 100% like yours ? Commented Jun 7, 2020 at 15:54

2 Answers 2

2

In the above code you call the function a which creates and sets a local variable x and defines a nested function, but that function is never called. As such you do not see any prints.

Note that just calling b() in a is not a good idea - as this function will recursively call itself with no stop condition. Instead you could write it as follows:

def a():
    x=20

    def b():
        global x
        x=88


    print("before calling b", x)
    b()
    print("after calling b", x)
a()
Sign up to request clarification or add additional context in comments.

2 Comments

This looks just like a comment
@azro This is an answer.
0

It seems like what you really want is this code:

def a():
    x=20

    def b():
        global x
        x=88

    print("before calling b",x)
    b()
    print("after calling b",x)

a()

This code tests the effect of calling b from within a on the values of a variable x, local to a. There will be no effect, as x is not global. The output would be:

before calling b 20
after calling b 20

If you change the definition of b to:

def b():
    nonlocal x
    x=88

You will see the effect of modifying x:

before calling b 20
after calling b 88

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.