Question1/3 If we were replace break in code by continue... | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
- 1

Question1/3 If we were replace break in code by continue...

It will realy continue forever? while I < 5: if I = 6: break print(I) print('realy forever!?')

19th Jan 2017, 11:48 PM
Ananda Kodikara
Ananda Kodikara - avatar
1 ответ
- 1
Yes. Here's why: First off, I'm going to address if statement and break last. I want to focus on and explain all the lines of the while-loop first. So first off, you have an 'if' statement that "should" check if 'I' is equal to 6. (I will point out an error on this line below) Then you print 'I'. That's the content of your loop. In this code, your loop will run indefinitely because the value of 'I' never changes. If you were to add another line like: I+=1 'I' would increment and each time you reach the top of the while loop, the test 'I < 5' would be True unless 'I' becomes greater than or equal 5. Now here is an exception. If 'I' was initialized to 5 before reaching the while-loop, once the loop is reached, it will never execute because 5 is not < 5. However, if 'I' was initialized to 0 before reaching the loop, the while loop will run and as it currently stands will run forever... really! Finally, let's look at the variable 'I' and the 'if' statement. As it stands, 'I' must be declared before use. Otherwise it's an error. Next, the test for the 'if' is 'I' = 6. This is a syntax error. You have an assignment, 'I = 6', where a conditional, 'I == 6', should be. Correct this line so it reads: if I == 6: break Then rerun. First thing you should realize is the break code will never be reached. Why? Because the loop will terminate once 'I' equals 5 and 5 < 6. Now let us assume you change the if statement again and add a line to increment 'I' like this: if I == 3: break i+=1 Once 'I' equals 3, this loop will terminate. Now going back to your original question about using a 'continue' instead of a 'break', if you were to use a 'continue', yes, the loop for run forever because the variable 'I' would never increment. Also, the last print statement will never be printed. So remember, there are 2 main ways to break out of a loop. The first is to satisfy the condition of the 'while' statement and the other is to use 'break'. I hope that answers your question.
20th Jan 2017, 1:59 AM
M King
M King - avatar