Infinite while loop with continue keyword - python

My problem - and I don't know why there is a keyword continue, which should leave the value of 3 and go further. In fact, I have a loop that is infinite - that is, it crashes the program.
tab = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
i = 0
while i < len(tab):
print(tab[i])
if tab[i] == 3:
continue
i+=1

It looks like you are trying to iterate through the list until you find a 3 then break. Do something like this:
items = [1,2,3,4,5]
for item in items:
if item == 3:
break
The keyword continue will pass to the next iteration of the loop, where break will stop the loop.

The continue keyword continues with the next iteration of the loop.
In your case, it prevents the statement i+=1 to be executed.
Here is what happens:
Loops through 0,1,2 just fine
When it evaluates tab[i] = 3 it proceeds with the next iteration of the loop and i+=1 is never executed, hence i remains 3 and never gets incremented. It keeps doing this forever.
If you want to exit the loop, you can use the break statement instead of continue.
For more information, you can read on the continue keyword here: https://docs.python.org/3/tutorial/controlflow.html

I think the answers here all assume that OP wanted to use break instead of continue.
However, if you need to use continue in a while loop, make sure you have an increment/decrement operation above the continue statement, because the continue statement jumps to the top of the while loop and, in your case, i remains 3.
Respectively, the continue statement in a do-while loop jumps to the bottom of the loop. So, in your case you have two options, either you increment above the continue or use a for-loop.
tab = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
i = -1
while i < len(tab):
i += 1
print(tab[i])
if tab[i] == 3:
continue
OR
for i in range(0,15):
if i == 3:
continue
print(i)

You're using the continue keyword, but I think you want break.
Your code is running forever because i never iterates past 3. Once i == 4, it enters your if statement and continues the loop. Since it continues, it never iterates after that.

Because you are using the continue keyword that skips the rest of the code.
Once i reaches 3, it skips over the i+=1 command. It appears that you want to use the keyword break. You could also do:
for i in tab:
print(i)
if i == 3:
break

If you are trying to skip the value "3" then
tab = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
i = 0
while i < len(tab)-1:
i+=1
if tab[i] == 3:
continue
//i+=1 => infinite loop
print(tab[i])

Related

While Loop Counter Confusion

I'm working with while loops and I'm just a bit confused on how to break out of it in the way that I want. So I've nested a for loop within a while loop:
x = True
y = 0
while x:
if y >= 5:
x = False
print('break')
else:
for x in range(7):
y += 1
print('test')
The output that I'm looking for is 5 tests printed out and one break. However, every time I run the program it prints out 7 tests before it goes to the break. I'm not exactly sure, but I think I'm just confused about something within while loops! If someone could explain this to me please let me know :) I have found ways around this, but I'd like to get an understanding of why it doesn't work.
This is because it's performing the entire for loop within the while loop therefore y will become 7 before it checks again. Removing the for loop will resolve this.
x = True
y = 0
while x:
if y >= 5:
x = False
print('break')
else:
y += 1
print('test')
y = 0
while y < 5:
print("test")
y += 1
print("break")
Would work.
There is no point in having another variable like "x" for the while loop when it allows for you to set the condition directly.
Because inner loop will complete before the next iteration of the outer loop. I.e. once the inner loop starts it does all 7 iterations before starting the next iteration of the while loop.
You can do this by just using one loop. Print out “test” increase counter and put in an if condition to break when counter is 5.
The reason 7 tests print rather than 5 is that your entire for loop is executed before you go back to the beginning of your while statement. I think your understanding is that, after one iteration of a for loop, you go back to the beginning of the while loop, but this is incorrect: your for loop is executed completely before going back to the beginning of the while loop.
After you step into the for loop, you increment y 7 times and print test 7 times. y is now >= 5, and you go back into your if statement. The if statement turns x false, thereby "turning off" the while loop, and a break statement is printed. If you just want to print out 5 tests and one break, it would be much easier to simplify your code as such:
y = 0
while True:
if y < 5:
print('test')
y += 1
else:
print('break')
break
Try
i = 0
while True:
if i == 5:
break
print('test')
i = i + 1

If statement returning False in While True loop (Python)

I expected that in this If statement, the variable 'i' would increment until it eventually equals 10, and subsequently 'if 10 < 10' would return False, breaking my while loop. But this code seems print until 10 and then get stuck in an infinite loop unless I add an else: break. Why?
i=0
while True:
if i < 10:
i = i + 1
print(i)
while X repeats when X equals to True so in while True it's always True. It only breaks with break statement.
In your code, you only check the value inside the while loop with if so neither you break the while loop nor you change True to False in while True.
If you want to use while:
i = 0
while i < 10:
i += 1
print(i)
Or
i = 0
while True:
if i < 10:
i += 1
print(i)
else:
break
Without while:
for i in range(10):
print(i)
while True
will make the loop run forever because "true" always evaluates to true. You can exit the loop with a break.
To achieve what you want to do, I would use
while i < 10:
print (i)
i++
That is because there isn't anything telling you to terminate the loop. So it will continue even after the if statement isn't satisfied.
This is why it is generally not a great practice to use while True
You can achieve the same thing with a for loop when the break condition is built into the loop:
for i in range(0, 10):
print(i)
If you want to use while True then you can go for:
i=0
while True:
i = i + 1
print(i)
if i == 10:
break
I think you need to understand a few things here, as you have set while True which means statement will never gets false so there is never end to while loop even if if condition gets fail. So the while loop will continue running till you interrupt.
The only way you can achieve this without break is like this, where you have a variable which will reset the condition of while loop to false when if loop fails
i=0
condition = True
while condition:
if i<10:
i=i+1
print(i)
else:
condition=False

Python break for loop

I am new to Python, but I think reserved words must have similar meaning in programming. However, I don't know why the break inside the 2nd if-condition breaks two for-loop.
I want to check if the list is empty or not, so I use a while-loop. It is supposed that if newList still has elements, it will stay in the loop2. However, after the break in con2, it goes directly to loop1 even newList still has element.
while list:
print ("loop1")
result = 'n'
for e in list:
print ("loop2")
result = 'n'
for h in longList:
print ("loop3")
for i in e.getList():
print ("loop4")
if (i == h.getId()):
print ("con1")
result = 'y'
break
if (result == 'y'):
print ("con2")
break
Your break statement is breaking from both loops because if you look just before you execute the first break statement, you assign the value y to the variable result. After you break from your first loop, the next line that gets tested is if (result == 'y'): and then you break again
while newList:
print ("loop1")
result = 'n'
for node in newList:
print ("loop2")
result = 'n'
for parent in parents:
print ("loop3")
for neighbourId in node.getNeighbours():
print ("loop4")
if (neighbourId == parent.getId()):
print ("con1")
result = 'y' # assignment
break # first break
if (result == 'y'): # occurs after the first break and will be true
print ("con2")
break # second break
else:
print('This loop was not terminated with a break statement')
else:
print('while loop ended')
Update:
In Python you can add an else clause to a loop and this else clause will only run if the loop has executed in full i.e never reached a break statement

Which loop does the break statement break?

In below code, which loop does the break statement break?
import time, sys
setT = '07:40'
while 1:
if time.strftime('%I:%M')==setT:
for mp in str(123):
print('the time is'+setT)
print('End')
break
Any break statement always breaks to the nearest outer loop
so in this case, it will break to the while loop
After the first while 1 the loop will break because you have break. So it will print once, and its the while loop that gets broken.

How to stop the whole loop?

I have a problem in the loop below for python.
It doesn't stop as soon as totalout=4, but only when the whole loop for scorein is over. (i.e. the thrid loop)
For example, if the totalout=4 in scorein number 2, it runs the loop till it reaches 10
#global value
totalturn=0
totalscorein=0
totalout=0
def main
numberofturn=int(input("Number of score:"))
no_turn=['1','2','3','4','5','6','7','8','9','10']
#while loop condition
while totalturn<numberofturn and totalout<10:
#increasement
totalscore+=1
#for loop for score
for t in range(1,numberofturn+1):
turns=s*1
print("\n\n\nThe turn"+no_turn[t]+":",turns)
#for loop for number to appear from list
for c in range (10):
#list for random number to appear
numscore = ['1','2','3','4','5','6','7','8','9','o']
#random choice from numscore list to appear
from random import choice
scorein=choice(numscore)
print ("\n\nScores :",scorein)
if scorein.isdigit():
totalscorein=totalscorein+int(scorein)
if scorein.isalpha():
totalout+=1
if totalturn==numberofturn:
print("\nTotal turn played:",totalturn)
elif totalout==4:
print("\nTotal turns played",totalturn)
break
else:
print("")
Do you want the break to break out of the 3 loops? I guess you are judging from the title of the question
In this case, since it is the end of the function, you could just replace break with return
Try changing the and operator to or. That seems to be what you want.
while totalscore<numberofscore or totalout<10:

Categories

Resources