I am really curious about this.
I have a for loop that is looping through a list. Inside the for loop I have a while loop that I want to loop through till a condition is met. When the condition of the while loop is met, stop the while loop and move to the next item of the list and start the while loop again.
Here is the example code:
course_ids = [1,2,3,4,5]
loop_control = 0
counter = 0
for ids in course_ids:
while loop_control == 0:
counter = counter + 1
if counter == 2:
loop_control = 1
The problem is that when the while loop condition is met, it breaks out of the for loop altogether.
How do I get the for loop to work as intended with a while loop inside of it?
loop_control == 1), it remains the case for each subsequent for loop iteration. Technically the for loop continued, the iterations just didn't do much.whilestructure will loop twice. On the first iterationcounterwill be set to1, on the second it will be set to2. Theif counter==2statement will then become valid. At which pointloop_controlwill be set to1. On the subsequent attempt to loop, the expressionloop_control==0will evaluate toFalseand thewhileloop will fail. The second iteration of theforloop will proceed. Any subsequent iteration of thewhileloop will fail sinceloop_controlwill still equal1.whileafter eachforloop iteration, you need to resetloop_control(and probablycounteras well) to0right before thewhile, not before thefor.python if counter != len(course_ids): loop_control = 0