Python For Loops
January 17th 2020 565

Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example:
Note:
The for loop does not require an indexing variable to set beforehand.
The range()
function
- It is type of iterator
- Creates a list containing arithematic progression
Syntax:
range(stop)
range(start, stop)
range(start, stop, step)
Note:
Loops will stop one position before the stop value
Note:
Step is the amount of increments per iteration
Example:
String Traversal
Even strings are iterable objects, they contain a sequence of characters.
Example:
The break Statement
With the break statement we can stop the loop before it has looped through all the items.
Example:
The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with the next.
Example:
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop".
Example:
The pass Statement
for
loops cannot be empty, but if you for some reason have a for
loop with no content, put in the pass
statement to avoid getting an error.
Example: