Reputation: 398
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?
Upvotes: 1
Views: 2444
Reputation: 398
you all are right.
I did not reset the while loop condition
I have added these lines after the for loop and it fixed the issue
if counter != len(course_ids):
loop_control = 0
Upvotes: 0
Reputation: 7744
Your assumption is wrong that it breaks out of the for loop altogether. It doesn't, it runs but the while condition is never True
and hence it never runs inside it.
You can also check this by adding a print statement inside the for loop and see its output.
course_ids = [1,2,3,4,5]
loop_control = 0
counter = 0
for ids in course_ids:
print("here")
while loop_control == 0:
counter = counter + 1
if counter == 2:
loop_control = 1
Output:
here
here
here
here
here
As you can see it ran 5 times as expected. You should also consider visualizing the code to get a better understanding, see here
Upvotes: 0
Reputation: 1392
You set loop control to 1 in the if statement. The while loop is set to only run if loop control is equal to 1. So basically the first time it runs, you set the condition to never run again.
If you were to reset loop control to zero on each iteration of the for loop, the while will run each time.
course_ids = [1,2,3,4,5]
# loop_control = 0 <-- Remove this line
counter = 0
for ids in course_ids:
loop_control = 0 # place this line and see it work more than once.
while loop_control == 0:
counter = counter + 1
if counter == 2:
loop_control = 1
Upvotes: 3