Access function variable outside of function?

前端 未结 2 1163
遥遥无期
遥遥无期 2021-01-16 20:33

So I\'m a beginner, and this is for a class I\'m taking. I know about return, but it\'s not letting me do what I\'m trying to do in this piece of code

T

相关标签:
2条回答
  • 2021-01-16 21:02

    This is a scope problem. You have to variables called flavor. One in global scope and one in function scope.

    If you want to access the global variable inside your function you need the 'global' keyword inside the function.

    The other possibility is to assign the return value of your function to the global variable flavor.

    Refer to [http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#more-about-scope-crossing-boundaries] for a complete explanation with examples.

    0 讨论(0)
  • 2021-01-16 21:25

    Variables inside functions disappear ("go out of scope") when the function returns.

    To get a value out of a function, you need to do two things:

    1. In the function - return a value, or values.

    2. When you call the function - save the value, or values. You do that by setting a variable equal to the result of the function: flavour = display_cookies().

    Consider this example:

    def answer_to_life():
        answer = 42
        return answer
    
    ans = answer_to_life()
    print (ans)             # output: 42
    

    Note that I've used a different variable name inside the function (answer) and outside (ans). You could use the same name, but that can confuse you early in your education.

    0 讨论(0)
提交回复
热议问题