fbpx

Loop Control

Continue, break, pass

There may be circumstances where you want to alter or interrupt the flow of the loop depending on a certain condition. The easiest way to do this is by using the keywords pass, continue, or break.

Continue

continue statement essentially cuts off any remaining commands within a loop, and jumps back up to the top of the loop to move onto the next iteration. This might be helpful if we want to skip an iteration depending on some condition. For example:

				
					for i in range(0, 6):
    if i == 2:
        continue
    print(i)
        
# Output:
# 0
# 1
# 3
# 4
# 5
				
			

Break

break statement will completely terminate the loop if it is executed, and is helpful to use if we don’t want to continue iterating once a given condition is met. For example:

				
					for i in range(0, 6):
    if i == 2:
        break
    print(i)
        
# Output:
# 0
# 1
				
			

Pass

Including a pass statement does not do anything to alter the flow of code. It is typically just used as a placeholder. Here is an example:

				
					for i in range(0, 6):
    if i == 2:
        pass
    print(i)
        
# Output:
# 0
# 1
# 2
# 3
# 4
# 5
				
			

Replit Practice

Loading...