python store variable in function and use it later

前端 未结 5 1584
星月不相逢
星月不相逢 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 18:41

    Hmmm, unless I am misunderstanding, this is a classic non-solution to a non-problem.

    Why not just use the language as it is?

    while condition:
    
       x = something
       y = else
       z = altogether
       ...
       save_state = (x,y,z)   ## this is just a python tuple.
       ...
       # do something else to x, y and z, I assume
       ...
       x, y, z = save_state
    

    Depending on the type of x, y and z you may have to be careful to store a copy into the tuple.

    (Also, your indentation is wrong, and there is no such thing as end in python.)

    Update: Ok, if I understand better, the question is just to be able to use the previous value the next time through. In the simplest case, there is no problem at all: the next time through a loop, the the value of x,y, and z are whatever they were at the end of the previous time through the loop (this is the way all programming languages work).

    But if you want to be explicit, try something like this:

     x_prev = some_starting_value
     x = some_starting_value
     while condition:
          x = something_funky(x_prev)
    
          .... other stuff ....
    
          x_prev = x
    

    (but again, note that you don't need x_prev at all here: x=something_funky(x) will work.)

提交回复
热议问题