Introduction to For Loops
Much like how a while loop will repeat its own block of code, For Loop will also repeat its own block of code.
For loops don’t depend on a conditional statement being
True
.For loops will repeat a finite amount of time dependent on the size/length of the iterating sequence.
A for loop is started by using the keyword:
for
__iterating_variable__
is a label that you create to represent the individual items in the sequenceNo matter the iterating variable, the code within the for loop will execute
The code within the for loop executes repeatedly until the iterating variable runs out of items to represent from the sequence
What is a Sequence?
Sequence is a collection of items or things.
The sequence can be ordered(least to greatest) or unordered(shuffled)
These sequences will have a beginning and an end; therefore, they are finite
We can determine the size of the sequences
Examples:
List of integers:
[2,3,5,7,11,13]
A string:
"Sequence"
is a sequence of 8 charactersIn Python, a data type that is classified as iterable will be able to iterate within a for loop
Examples: Lists, Strings, Tuples, Dictionary
Code Example 1
Explanation:
The label
character
is used as a label to represent each single item from the iterating sequence for each iterationThe variable
word
is a string that has the characters:Hello!
Since
character
represents individual items, we were able to grab the items in the sequence in order and one-by-one
Code Example 2
Explanation:
In Code Example 2, the iterating variable
character
is not used within the for loop’s code blockThe string of
Goodbye!
is outputted 6 times.There are 6 outputs because variable:
word
has 6 items in the sequence
Last updated