0

Here is my stupid question: say we have a simple for-loop as follows:

import time

for i in range(6):
   x = i ** 1
   time.sleep(5) #sleep for 5s
   print(x)

While this loop is running (e.g. 11 s after we initiated the code), we decide to change/update x = i ** 1 to x = i ** 2 to get the output for the new x. Is there any way to do this, i.e. manually updating the variable inside a loop while it's running (and obviously we do not want to use input).

Thanks!

MathPass
  • 3
  • 2

1 Answers1

0

Since python is by default thread-locking, you cannot change the value of your variable without designing your code to do so. However, if you are using threads (see threading docs here), you can create two different threads which will run parallel, asynchrously. By accesssing the same variable (needs to be in same scope or global), you can change it while your loop is still running.
It is, however, not best practice to do so since most of the time you can't tell which operation will happen first due to how CPUs will process their work.

white
  • 601
  • 3
  • 8