Table of contents
In Python, a for loop is a control structure that allows you to iterate over elements in an iterable, which is a general term for any object capable of producing a sequence of values. I've covered the usage of for loops with lists in detail in my earlier blog post titled 'Data Types.' I plan to explore similar iterations with tuples and dictionaries in upcoming articles. The most common use of a for loop is to execute a block of code repeatedly for each item in the iterable.
Structure of For Loops
variable
represents a temporary variable that takes on the value of each item in the iterable during each iteration of the loop. You can choose any valid variable name.iterable
is the object over which you want to iterate. It can be a string, tuple, range, dictionary, or any other iterable object.The colon
:
at the end of the first line is crucial as it indicates the start of the loop block.The code inside the indented block below the
for
statement is what will be executed for each item in the iterable.
Example 1
Type the below code to your code editor.
name: str = "William Wilberforce"
: This line declares a variable namedname
with a type hintstr
to indicate that it's expected to store a string. It's then assigned the string value "William Wilberforce."for char in name:
: This line initiates a for loop. It tells Python to iterate over each character in thename
string. The variablechar
is a temporary variable that will take on the value of each character during each iteration.print(char)
: Inside the for loop, this line is responsible for printing the current character represented by thechar
variable. During each iteration of the loop, a character is printed.
When you run this code, it iterates over the characters in the name
string "William Wilberforce" one by one, and for each character, it prints that character. The result is that it prints each character in the name on a new line:
Example 2
Please enter the following code, which defines a list containing the aliens from the Ben 10 series.
ben_10_aliens: list = ["Heatblast", "Four Arms", "XLR8", "Diamondhead", "Upgrade"]
: This line declares a variable namedben_10_aliens
and explicitly specifies its type as a list using type hinting (list
). It then assigns this variable a list containing the names of several Ben 10 aliens.for alien in ben_10_aliens
: This line starts a for loop. It iterates over the elements in theben_10_aliens
list, and during each iteration, thealien
variable takes on the value of the current element (in this case, each alien's name).print(alien)
: Inside the for loop, this line is responsible for printing the value of thealien
variable during each iteration. It prints the name of each alien.
When you run this code, it iterates through the ben_10_aliens
list, one alien at a time, and prints the name of each alien. The output is the list of Ben 10 aliens with each name printed on a separate line due to the print(alien)
statement inside the for loop as shown below.
Example 3
Let's enhance the complexity of the code. Please input the following code into the text editor.
Some concepts need some explanation. If you look at the for loop, you will notice a certain word called range
. That is an inbuilt function that is commonly used in for loops to generate a sequence of numbers. The range()
function generates numbers starting from a specified start (by default, it starts at 0) up to, but not including, a specified end value.
In the line of code for i in range(num_items):
, the range(num_items)
generates a sequence of numbers starting from 0 and ending at num_items - 1
.
Here's how it works:
If
num_items
is 5, for example,range(5)
generates the numbers 0, 1, 2, 3, and 4.If
num_items
is 10,range(10)
generates the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
This is a common convention in programming languages, where counting often starts from 0 (zero-based indexing). So, to iterate through num_items
items in a sequence, the loop uses range(num_items)
, and i
takes on the values from 0 to num_items - 1
, effectively iterating through all the items in the sequence.
With that out of the way, let's explain the code.
def create_list():
: This line defines a Python function namedcreate_list()
.num_items = int(input("Enter the number of items you want to add to the list: "))
: This line prompts the user to enter the number of items they want to add to the list. Theinput()
function takes user input as a string, andint()
is used to convert it into an integer. The entered number is stored in the variablenum_items
.my_list = []
: This line initializes an empty list namedmy_list
that will store the items entered by the user.for i in range(num_items):
: This line starts a for loop that will iteratenum_items
times. It uses therange()
function to generate a sequence of numbers from 0 tonum_items-1
, which represents each iteration.item = input(f"Enter item {i + 1}: ")
: Inside the loop, this line prompts the user to enter an item for the list. Thef-string
is used to include the iteration number (i + 1) in the prompt to make it clear which item is being entered. The entered item is stored in theitem
variable. Let's explain theinput(f"Enter item {i + 1}:")
more clearly:.
input(...)
: This function is used to take user input from the keyboard. Whatever the user types is treated as a string..
f"Enter item {i + 1}:"
: This is an f-string, which is a feature in Python that allows you to embed expressions within string literals..
"Enter item "
: This is a string literal that provides a prompt to the user, asking them to enter an item..
{i + 1}
: Inside the f-string,{}
is used to enclose an expression. Here,i + 1
is the expression..
i
is the loop variable, representing the current iteration of the loop. It starts at 0 for the first iteration..
i + 1
is used to adjust the iteration count to make it more user-friendly. Since many people count items starting from 1 (not 0), adding 1 toi
ensures that the prompt displays "Enter item 1:" for the first iteration, "Enter item 2:" for the second iteration, and so on.my_list.append(item)
: This line adds the user-entereditem
to themy_list
using theappend()
method. This step accumulates the items in the list during each iteration of the loop.After all the iterations are complete, the function
create_list()
returns the populated listmy_list
.my_created_list = create_list()
: This line calls thecreate_list()
function and stores the returned list in themy_created_list
variable.print("The created list is:", my_created_list)
: Finally, this line prints the content of themy_created_list
to display the list of items entered by the user.Run the program and let's assume the user types the number 5. After the user enters the number 5 as the number of items they want to add to the list and provides the items "Banana," "Orange," "Watermelon," "Mango," and "Pineapple," the program executes the following line of code:
print("The created list is:", my_created_list)
This line prints the content of the
my_created_list
variable, displaying the list of items entered by the user. In this specific example, the user's input results in the following output:
That concludes our discussion on for loops. It became evident that example 3 needed more explanation than initially thought. Consequently, I focused on breaking down the code into manageable parts, especially the for loop. It's worth mentioning that previous articles have covered Python functions and lists in depth.
Moving forward, our exploration of Python programming will shift to more advanced topics, including dictionaries and tuples. In the upcoming article, we'll be focusing on Python tuples. Stay tuned for an interesting discussion!