0
What is the use of "Continue" in while loops?
i = 1 while i<=5: print(i) i+=1 if i==3: print("Skipping 3") continue #when I run the above code, 1 2 Skipping 3 '3' 4 5 I was wondering, why isn't the number 3 skipped? I can't see the power of "continue" here, it did nothing. I was looking at the comments and found out that other people got the expected output(with 3 being skipped). Can anyone help me?
3 Antworten
+ 3
As Abhay said you are printing before the if statement so when you continue you go back at the beginning of the loop since there is nothing after continue statement the result will not differ so you have to place the print after the if statement like this
i = 1
while i<=5:
i+=1
if i==3:
print("Skipping 3")
continue
print(i)
+ 2
Continue is use to sent the control back to the start of loop as you must know
So in your case when i==3 ,it prints skipping 3 and then control goes back to the loop ,print(i) prints 3 and then increments it
Place print(i) and i+=1 after if statement ,you will see the difference
+ 1
Thank you guys for the fast reply
makes sense now