The for Loop

Explore the essential features and usage of "for" loops for effective iteration in programming.

A for loop uses an iterator to traverse a sequence, such as a range of numbers, the elements of a list, or the characters in a string. In simple terms, the iterator is a variable that goes through the list. The iterator starts at the beginning of the sequence and ends when it reaches the end.

Structure

In a for loop, we need to define three main things:

  1. The name of the iterator

  2. The sequence to be traversed

  3. The set of operations to perform

The loop always begins with the for keyword. The body of the loop is indented to the right:

Press + to interact

The in keyword specifies that the iterator will go through the values in the sequence/data structure. Notice the colon at the end of the for statement.

Forgetting to put the colon at the end is a common mistake that beginners make. Be mindful of that.

Looping through a range

In Python, the built-in range() function can be used to create a sequence of integers. This sequence can be iterated over through a loop. A range is specified in the following format:

Press + to interact
range(start, end, step)
...
Access this course and 1400+ top-rated courses and projects.