Access function variable outside of function?

前端 未结 2 1164
遥遥无期
遥遥无期 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: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.

提交回复
热议问题