+ 2

Differences between the break statement and continue in python?

21st Oct 2021, 10:46 AM
Arc
6 Respuestas
+ 2
Break statements exist in Python to exit or “break” a for or while conditional loop. When the loop ends, the code picks up from and executes the next line immediately following the loop that was broken. Example: numbers = (1, 2, 3) num_sum = 0 count = 0 for x in numbers: num_sum = num_sum + x count = count + 1 print(count) if count == 2: break In this example, the loop will break after the count is equal to 2. The continue statement is used to skip code within a loop for certain iterations of the loop. After the code is skipped, the loop continues where it left off. for x in range(4): if (x==2): continue print(x) This example would print all numbers from 0-4 except 2.
21st Oct 2021, 2:52 PM
Arun Jamson
Arun Jamson - avatar
+ 4
break comletely jumps out of loop continue jumps back to the beggining of the loop
21st Oct 2021, 10:59 AM
Slick
Slick - avatar
+ 3
The Difference is that a break statement will break or stop a loop even if its required iterations is this incomplete. However The continue statement is used to quickly stop the current iteration of a loop and continue on to the next iteration of the loop. In simple terms, Break Statement will stop the whole loop once its executed. Continue Statement will stop the current iteration of the loop and continue on. Example 1: x = 0; y = 0; for x in range (0, 10): if x % 2 == 0: continue; y += 1; print(y); the output is 5 because when 5 is even it continues or skips to the next iteration that is odd. Example 2: x = 0; y = 0; for x in range (0, 10): if x % 2 == 0: break; y += 1; print(y); Here the output is 0 because on the first iteration the value of x is 0 which is even which causes breaks the for loop
21st Oct 2021, 11:05 AM
Danielle Bagaforo Meer
Danielle Bagaforo Meer - avatar
+ 2
Slick you made a little mistake which answering. The continue statement doesn't jump back to the beginning of the loop, it jumps to the start of the next iteration. There's s big difference between the two =)
21st Oct 2021, 11:51 AM
Rishi
Rishi - avatar
+ 2
break: break it! continue: skip as condition and continue the loop ✌
21st Oct 2021, 11:53 AM
Co.De
Co.De - avatar
+ 2
break is used to come out from loops continue is used to skip particular condition or iteration based on condition mentioned by developer Note : it is not possible to use break statement in “if” condition
22nd Oct 2021, 8:38 AM
sree harsha
sree harsha - avatar