In this tutorial we are going to learn :

• For Loops
• Iterables
• The range () Function
• Nested Loops

### For Loop

We use loops for iterating over a sequence ( string, list, tuple, dictionary, set ) or any
other iterable objects

### Iterables

Examples of iterating lists and strings.

• ##### Iterating a List

Example :

Example of iterating a list.

``````# for loops

my_list = [1, 2, 3, 4, 5]

# iterating a list
for x in my_list:
print(x) ``````

##### Iterating a String

Example :

Example of Iterating a String

``````# for loops

name = "James"

# iterating a string
for x in name:
print(x) ``````

### The range () Function

We use the range () function to generate a specified number of loops on a set of code.

Example :

``````for number in range(5):
print("Hello ") ``````

Note :

range () function here is not the values 0 to 5 , values 0 to 4 . In our program
range (5) function will generate numbers 0 to 4.
Let’s Look at the example below. You can see the range() function’s index numbers
too

``````for number in range(5):
print("Hello", number) ``````

• range() function defaults to 0 as a starting value. But we can determine the starting value by adding a new parameter.

Example :

You can see that our index numbers generated from 1 to 4.

``````for number in range(1,5):
print("Hello", number) ``````

• We can also set the number‘s increment value by adding a new third parameter.

Example :

• Generated from 1 to 10.
• The increment value is 2.
``````for number in range(1,10,2):
print("Hello", number) ``````

### Nested Loops

Nested loops are basically a loop inside a loop.

Example :

In this program,

• the inner loop will be executed one time for each iteration of the outer loop.
``````for number in range(3):
for x in range(2):
print(f"({number}, {x})") ``````
0 0 vote
Article Rating
Subscribe
Notify of