Learn for Loops in Python using simple examples.

Example 1: Loop List and Numbers

A simple example to print names and numbers.

This example will teach you the following:

  1. How to loop through list in python
  2. How to loop through numbers via the range() function.

Step 1: Create Project

Create python project or file named main.py.

Step 2: Write Code

Add the following code:

# Loop through list and print them
names = ['Karen', 'Daudi', 'Keegan']
for  name  in  names :
    print(name)

# Print numbers 0-9 via range()
for  x  in  range ( 10 ):
    print(x)

Step 3: Run

Run the code by navigating to the project directory:

cd your_project_folder

Then execute:

python main.py

You will get the following:

Karen
Daudi
Keegan
0
1
2
3
4
5
6
7
8
9

Categorized in: