For the code below, after the first instance where the IF statement is false (i.e. for i=9), I understand that we go to the print("something") step however, my question is why does it infinitely print "something" and "somethingelse" instead of printing these two just once each then just ending? I mean we have no step after the print of these two that tells it to go back to the if statement and test again with i = 9 (that would lead to an infinite loop)..
i=1
while True:
if i%9 != 0:
print ("inside if")
i +=1
continue
print("something")
print("somethingelse")
Your print statements are inside of a While True: loop with no exit criteria. That is precisely why.
while True:
Means that while I do not have a statement somewhere to stop or a break to stop the algorithm, it will keep entering in the while loop.
Therefore, what you made is an infinite loop and that's why it keeps printing the same stuff.
i=1
while True:
if i%9 != 0:
print ("inside if")
i +=1
break
print("something")
print("somethingelse")
#output
"inside if" -> breaks after `i=1` because `1%9=1`
"something"
"somethingelse"
i=1
kak = True
while kak:
if i%9 != 0:
print ("inside if")
i +=1
kak = False # --> something to tell the algorithm, hey! stop!
print("something")
print("somethingelse")
Python newbie. I am trying to print number after taking input from user using while loop.
my code takes int from user and then runs the loop. after printing the first number the code asks to continue after which the loop will continue.
My code is below:
i = 1
ans = 'n'
x = int(input("enter a number to loop: " ))
while(i<x):
print('\n')
print(i, end= " ")
ans = input('\ndo you want to print the next number? ')
if ans == 'y':
i += 1
else:
print('thanks')
The code is doing and extra loop and then after getting the answer terminates the loop. On top of that on the last loop if the answer is 'n' it keeps running.
You just have to add a break statement in your code, right before the print("thanks") line. That will exit the loop.
else:
break
print('thanks')
All loops will continue unless told to break or become false.
Break and continue are very important in programming. I suggest you read this https://www.tutorialspoint.com/python/python_loop_control.htm
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])
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
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: