python store variable in function and use it later

前端 未结 5 1503
星月不相逢
星月不相逢 2021-02-06 18:01

is it possible to store a variable from a while loop to a function and then call that same variable from the function at the end of the loop

for eg:during while loop, p

5条回答
  •  遇见更好的自我
    2021-02-06 19:01

    As others have stated, there is probably a more suitable choice than this, but it might be convenient in some situations (perhaps in a REPL). Here's a simple function that does what you want with any number of values.

    def store(*values):
        store.values = values or store.values
        return store.values
    store.values = ()
    

    Example

    >>> store(1, 2, 3)
    >>> a, b, c = store()
    >>> print a, b, c
    1 2 3
    >>> store(4, 5)
    >>> a, b = store()
    >>> print a, b
    4 5
    

提交回复
热议问题