Home > Software engineering >  Freeze variable False / True to change - make it immutable after first change
Freeze variable False / True to change - make it immutable after first change

Time:04-28

hope you can help me out.

Default state of the variable is set to "False" and within the "while True" loop I have "if/else" statement which can change the variable to "True". I would like to keep the variable "True" even the circumstances within the while loop will change in the future.

How can I "freeze" the variable's state? Make it immutable after first one change?

Thanks all who can help.

CodePudding user response:

x = False
while <condition>:
  if <another-condition>:
    x = True
  # ... and do not update x anywhere in the loop

CodePudding user response:

You can set the condition once the pointer is in the area and then never change it:

pointer_in_area = False

while True:             # main loop
    # move pointer
    if pointer in area: # condition to set the flag
        pointer_in_area = True
    if pointer_in_area:
        # do stuff, now "pointer_in_area" is always True

You can further extend this to two variables if you need to track both the current state of the pointer (NOW) and the previous state (was ever in the area):

pointer_in_area = False
pointer_once_in_area = False

while True:
    # move pointer
    if pointer in area:
        pointer_in_area = True
        pointer_once_in_area = True
    if pointer_in_area:
        # do stuff that requires pointer to be in area NOW
    if pointer_once_in_area:
        # do other stuff that requires pointer to have been once in area
  • Related