Break For Loop In Python

Python for loop is used to iterate and enumerate over lists, dictionaries, tuples etc. By default the for loop iterate over the items according to the specified conditions. There are different ways to break the for loop. We can use the break keyword in order to break for loop for the specified condition.

Break for Loop with break Keyword

The break statement is used to break the current loop which can be while or for loop. Generally, a condition is specified in order to execute a break statement. In the following example, we will check every item in the for loop and break the for loop if the item is equal to 3.

numbers = [1,2,3,4,5,6]

for i in numbers:
   if i==3:

The output of the for loop will be like below.


Bread for Loop with CTRL+C Keyboard Shortcuts

Python scripts can accept inputs named interrupts during executions. The CTRL+C is a popular i┼čnterrupt used to break current program execution which can also break the current loop too. In the following example, we run an endless loop that does not end unless the CTRL+C break.

for True:
   print("I go to the infinity...")

Press the CTRL+C keys that break the infinite for loop.


Leave a Comment