Search code examples
pythonvariableswhile-loopfixed

How to keep variables fixed within a while loop


I have two variables (variable_1 and variable_2). They are outputs of an algorithm and they are always different, since the algorithm contains some random part.

And I have a very long and complex function afterwards, that takes these variables as inputs. Its basic structure is:

def function(variable_1, variable_2):
    switch = True
    while switch:
      variable_1
      variable_2
      inner_function(variable_1, variable_2):
         ~changes variable_1 and variable_2 randomly~
      ~changed variable_1 and variable_2 are then transformed with data structure comprehensions.~
      ~in the end, there is a condition. If variable_1 and variable_2 meet this condition, switch is turned to False and the function ends. If not, the while loop shall start again, but with the original values of variable_1 and variable_2.~

The intention of the function is to output the changed variables. The problem is that it does not work. If the while loop runs through one iteration, and the switch is still True at the end of this iteration, variable_1 and variable_2 are not set back to their original values. How can I do this? (Please keep in mind that I do not want to fix variable_1 and variable_2 for my entire code that comes before or afterwards).

Sorry for not giving a minimally reproduceable example. I could not come up with one, considering the length and complexity of the function.

Edit: If I hardcode the variables (meaning that I write variable_1 = "its value" and variable_2 = "its value" above the inner function, it works. But I do not want to do this.


Solution

  • So you just need to make a deepcopy:

    import copy
    
    def function(variable_1o, variable_2o):
        switch = True
        while switch:
          variable_1 = copy.deepcopy(variable_1o)
          variable_2 = copy.deepcopy(variable_2o)
          inner_function(variable_1, variable_2)