[Python] Problem in defining a variable in a function call [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 27, 2024.

  1. Stack

    Stack Membro Participativo

    I've been reading the book Think Python by Allen Downey. I've read about function calls and stack diagrams, and that if you define a variable inside a function, its value will not be remembered outside that function.

    I've also understood all the examples given in the book in the chapter on functions. However the following program has got me confused:

    def k():
    print(h)

    def l():
    h=1
    k()

    l()


    Upon running it, the following error shows up:
    NameError: name 'h' is not defined

    Before running it, I thought that it would have worked as in my understanding, calling l makes a function frame of l and h is defined in that function frame, then k is called in the same frame, and a frame of k is also created, but since h variable is already defined in the frame which k has been called, k should have no problem in printing value of h.
    Now learning from this code I hypothesised that a variable if defined inside a function will strictly be remembered only in the same function, and not even in the function called inside it.

    But that is proven wrong by the following program:

    def k(h):
    print(h)

    def l():
    h=1
    k(h)

    l()


    This print 1 correctly. Now I get that in the second example the h function takes 1 argument. But still the value of that argument is assigned to the h variable in the function that called it, similar to example 1. But in one it remembers what h is and in another it doesn't.
    Please explain in terms of what python is doing, no simplification is demanded!

    Continue reading...

Compartilhe esta Página