The for Loop
Explore the essential features and usage of "for" loops for effective iteration in programming.
We'll cover the following...
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:
The name of the iterator
The sequence to be traversed
The set of operations to perform
The loop always begins with the for
keyword. The body of the loop is indented to the right:
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:
range(start, end, step)