简体   繁体   中英

Modify a python variable which is inside a loop

I have been trying to make a code that requires modification of a variable that is inside a loop.

a = 1
b = 2
while a<b:
    print(b)

now I want to change the value of b while the loop is running. I have tried to find an answer but could not do so. Can it be possible that I use this loop with an initial value of b and terminate this loop automatically and start a new one when variable b is modified to something else? How would that be possible? Note: I want to modify the var b from outside.

Further Explanation:

The code should be designed in such a way that a variable used to check the condition of the while loop can be modified when the loop is already running. Let's say a user wants to use this while loop as a function, he passes variables in the function to start the loop. Now he wants to change the variable value (in the above case var b), which is used in the while loop condition.

def start_loop(a,b):
   while a<b:
     #more codes will be included here
     print('The loop is running infinitely')



#call the function 
 start_loop(1,2) 
 Consol: The loop is running infinitely....

The loop is running infinitely since the loop is already running I can not ask the while loop to change the value of var b. I am looking for a solution that can handle this situation. How a user can modify "var b" from outside as the loop is already running?

Or how can I call the same start_loop() function with the modified value of var b? Doing so should result in the termination of the older loop and the start of this new loop.

I hope I'll find the answer here:) Thanks.

If you want to do what you said at the same time as running the loop, maybe the content of this link will help you pytho.org . If the solution is published, visit these links: eval() , exec()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM