Introduce For Loops and Iteration
In this step, you will learn about the for loop in Python. A for loop is used to iterate over a sequence, such as a list, tuple, or string. Iterating means performing an action for each item in the sequence, one by one.
First, let's use a for loop to print each element of a list.
In the WebIDE file explorer on the left, you will see a list of files. Find and open the file named for_loop_example.py. Add the following Python code to it:
## Define a list of numbers
numbers = [1, 2, 3, 4, 5]
## The for loop iterates over each item in the 'numbers' list.
## In each iteration, the current item is assigned to the 'number' variable.
for number in numbers:
## This code block is executed for each item.
print(number)
Save the file by pressing Ctrl + S.
To run the script, open the integrated terminal by clicking Terminal -> New Terminal at the top of the WebIDE. Then, execute the following command:
python for_loop_example.py
You should see the following output, with each number printed on a new line:
1
2
3
4
5
for loops can also iterate over strings. Let's try this in a new file. Open the file string_loop.py from the file explorer and add this code:
## Define a string
message = "Hello"
## Iterate over each character in the 'message' string
for char in message:
## Print each character
print(char)
Save the file and run it from the terminal:
python string_loop.py
The output will be:
H
e
l
l
o
This demonstrates that a for loop can process any sequence, treating a string as a sequence of characters.