Scripting >> Python >> Examples >> Loops >> Using break and continue in for or while loops

break

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.  If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop

 

Example 1: using break in a for loop

Code
for val in "string":
    if val == "i":
        break
    print(val)
print("The end")
Output
s
t
r
The end
 

 

 Example 2: using break in a while loop

Code
i=0
string="string"
while True:
    val=string[i]
    if val == "i":
        break
    print(val)
    i+=1
print("The end")
Output
s
t
r
The end

 

continue

The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration

 

 Example 3: using continue in for loop

Code
for val in "string":
    if val == "i":
        continue
    print(val)
print("The end")
Output
s
t
r
n
g
The end

 

 Example 4: using continue in while loop

Code
i=0
string="string"
while i < len(string):
   val=string[i]
   i+=1
   if val == "i":
      continue
   print(val)
print("The end")

 
Output
s
t
r
n
g
The end