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.
# For Loop Format
for __iterating_variable__ in __iterating__sequence__:
your code here
# end of for loopA 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
Code Example 1
# Using a for loop with a string
# Purpose: Output individual letters of a word.
word = 'Hello!'
for character in word:
print('Current Character:', character)Explanation:
The label
characteris used as a label to represent each single item from the iterating sequence for each iterationThe variable
wordis a string that has the characters:Hello!Since
characterrepresents individual items, we were able to grab the items in the sequence in order and one-by-one
Code Example 2
# Using a for loop, but ignoring the iterating variable
# Purpose: Repeat a message
word = 'Hello!'
for character in word:
print('Goodbye!')Explanation:
In Code Example 2, the iterating variable
characteris not used within the for loop’s code blockThe string of
Goodbye!is outputted 6 times.There are 6 outputs because variable:
wordhas 6 items in the sequence
Last updated