Turn Messy Text into Structured Insights With AI. Join Greg Live: Dec 4th, 2024
Leverage
Glossary

For Loop

Python for loop basics and controlling iteration with continue and break

In Python (and really general programming), loops are a fundamental building block of data analysis and computer science in general. The for loop is an extremely popular loop that should be mastered by all practitioners.

The Python For loop will iterate through an object and “do something” to each item. The loop will stop when it reaches the end of your iterable, or you tell it to stop.

for i in range(3):
  print (i)
 
>>> 0
>>> 1
>>> 2

Python For Loop Continue

You can ‘continue’ or stop the current iteration of the loop via the continue command. Python continue will move on to the next item in your script without running the remaining code. See an example below.

For Loop Break

Python break will ‘break’ your for loop and stop it all together. This means your for loop will stop executing and not iterate on any more items.

This is especially useful when you’re running your for loop until a certain condition. When that condition is met, you can stop your loop and move on. See an example below.

Let’s take a look at a python for code sample.

Link to code

On this page