Python For Loop

The Python For Loop is used to repeat a block of statements until there is no items in Object may be String, List, Tuple or any other object. Let us see how to write Python For Loop, For loop range, and for loop with else block with practical examples. Before we get into the details, let us see the syntax of the Python For Loop:

Python For Loop Syntax

The syntax of the Python For Loop in is as follows:

for item in Object:
     Statement 1
     Statement 2
     ………
     Statement n

If you observe the above Python for loop syntax, Object may be anything you want to iterate. For instance String or Python Lists so on.

  • Compiler starts with Object means, it will iterating object and then it will assign the first value to item. For instance our object is a string and value is Python, compiler will assign P to item
  • Next, it will execute the statements inside the For loop.
  • After completing the statements, compiler will goto the Object and assign next value to the item
  • Process repeats until there is no items in Objects.

Python For Loop Flow Chart

The flow chart of Python For Loop

FOR LOOP FLOW CHART

The execution process of the for loop in python is:

  1. Initialization: We initialize the variable(s) here. For example i=1.
  2. Items in Sequence / Object: Compiler will check for the items in Objects. For example, individual letters in String word. If there are items in sequence ( True) then it will execute the statements inside the for loop. If there is no item in sequence ( False) then it will exit from the loop
  3. After completing the every for loop iteration, compiler will traverse to next item.
  4. Again it will check for the new items in sequence. As long as the items in sequence, the statements inside the Python for loop will be executed.

Python For Loop Example

Use Python for loop to extract individual words from string and extract the data from Python List

# Python For Loop - String Example

Str = "TutorialGateway"
for word in Str: # First For Loop
    print("Letters are: ", word)
  
print("----This is Outside String For Loop---")
print(" ")

# Python For Loop - List Example
Countries = ['India', 'U K', 'U S A', 'Australia']
for Country in Countries: # Second For Loop
    print("Countries are: ", Country)
    
print("---This is Outside List For Loop")

The Output of the Python For Loop

Letters are: T
Letters are: u
Letters are: t
Letters are: o
Letters are: r
Letters are: i
Letters are: a
Letters are: l
Letters are: G
Letters are: a
Letters are: t
Letters are: e
Letters are: w
Letters are: a
Letters are: y
----This is Outside String For Loop---

Countries are: India
Countries are: U K
Countries are: U S A
Countries are: Australia
---This is Outside List For Loop

First, we declared a string variable called Str and assigned value as “TutorialGateway”

Str = "TutorialGateway"

Used the Python for loop to iterate through the string and display individual letters

for word in Str:
    print("Letters are: ", word)

We used two Python print statements outside the for loop. These statements will be executed once the compiler exit from first for loop

print("----This is Outside String For Loop---")
print(" ")

Now, the compiler will enter into List example (Second For Loop). First we declared Countries List and assigned the following values

Countries = ['India', 'U K', 'U S A', 'Australia']

We used the python for loop to iterate through the Countries List and display the individual list items

for Country in Countries: # Second For Loop
    print("Countries are: ", Country)

We used print statement outside the Python for loop. This statement will be executed once the compiler exit from second for loop

print("---This is Outside List For Loop")

It is too big to explain the first for loop. So, we will explain the second Python example with iteration. Please use the same technique to understand the first example

We used the Countries List for second for Loop

Countries = ['India', 'U K', 'U S A', 'Australia']

Python For Loop First Iteration

For the first Iteration, Country = ‘India’. It means there are some items in Object. So, Compiler will execute the print statement inside the for loop

For Loop Second Iteration – Country = ‘U K’. It means there are some items in Object. So, compiler will execute the country name.

For Loop Third Iteration – Country = ‘U S A’. It prints the statement inside the for loop

For Loop Fourth Iteration – Country = ‘Australia’. It executes statement inside for loop.

For the fifth iteration, there will be no items in the object to assign for Country variable so, the compiler will exit from for loop

Python For Loop range Example

The syntax of the Python For Loop range function is

for item in range(Start, End, Steps):
     Statement 1
     Statement 2
     ………
     Statement n

The Python for loop range has three arguments:

  • Start: This is the optional argument and if you omit this argument then python range function will start looking from 0.
  • End: The for loop range argument will notify the compiler about the range end position. Remember, if you specify 10 as end value then python range function will display up to 9.
  • Steps: This is the optional argument and if you omit this argument then python range function will increment the value by 1.

Python For loop in Range with two arguments

This Python range program will display the numbers from 0 to 4.

# Python For Loop with Range Example

for number in range(0, 5):
    print("Current Number: ", number)

for loop in range output

Current Number: 0
Current Number: 1
Current Number: 2
Current Number: 3
Current Number: 4

Python For Loop First Iteration – for number in range(0, 5)

for 0 in range(0, 5) – Condition is True
print statement will print number 0

For Loop range Second Iteration- for 1 in range(0, 5) – Condition is True. The print statement will print number 1

Python range Third Iteration- for 2 in range(0, 5) – Condition is True. So, it prints 2

Fourth Iteration- for 3 in range(0, 5) – Condition is True. So, it prints 3

Fifth Iteration- for 4 in range(0, 5) – Condition is True. So, it prints 4

For the sixth iteration, for 5 in range(0, 5) – Condition is False. So, program will be terminated.

Python For Loop Range with three arguments

In this example, We used three arguments in python for loop range

# Python For Loop with Range Example 1
for number in range(9, 14):
    print("Current Number: ", number)
print("")

# Python For Loop with Range Example 2
for num in range(5, 18, 2):
    print("Current Number: ", num)

Python For loop range with three arguments output

Current Number: 9
Current Number: 10
Current Number: 11
Current Number: 12
Current Number: 13

Current Number: 5
Current Number: 7
Current Number: 9
Current Number: 11
Current Number: 13
Current Number: 15
Current Number: 17

Within the first for loop, we started the range at 9. So, the first for loop is displaying values from 9 to 13. Where as, in the second for loop, we used the step value as 2 so, the second for loop is displaying alternative values from 5 to 18.

Use Python For Loop range on String and Lists

This python for loop range program will show you, How to use python range function on non integers.

# Python For Loop - String Example
Str = "Python"
for word in range(len(Str)):
    print("Letters at index {0} is = {1}".format(word, Str[word]))
  
print("----This is Outside String For Loop---")
print(" ")

# Python For Loop - List Example
Countries = ['India', 'U K', 'U S A', 'Australia']
for Country in range(len(Countries)):
    print("Countries at index {0} is = {1}".format(Country,Countries[Country]))
Python For Loop Example 4

In this Python for loop range example, First we declared the string variable and assigned the value

Str = "Python"

In the next line we used python range function. If you observe the below code, we used the len function inside the python range function to calculate the string length.

for word in range(len(Str)):

It means, above for loop range code can also be written as

for word in range(len('Python')) 

for word in range(6): # Where 6 is the length of Str

So, it starts the iteration from 0 and end at 5

Python For Loop Else

The Python programming allows us to use the else statement with python For loop statements as well and it works like Python If Else statement.

  • If there are items in Sequence then statements in the For Loop will be executed
  • If there are no items in Sequence then statements inside the Python Else block will be executed. If we used Break statement to break the for loop then Else block will not executed

For Loop Else Syntax

The syntax of the Python for loop Else statement is as shown below:

for item in Object:
     Statement 1
     ………
     Statement n
else:
     Statements inside the else block

Python For Loop Else Example

This python for loop else example program allows the user to enter an integer. If the user entered value is below 100 then compiler will execute the statements in for loop. Otherwise, print statement inside the else block will be executed.

# Python For Loop Else statement Example

number = int(input(" Please Enter any integer below 100:  "))

for i in range(0, 100):
    if number == i:
        print(" User entered Value is within the Range (Below 100)")
        break
else:
    print(" User entered Value is Outside the Range (Above 100)")

For Loop Else statement output

Please Enter any integer below 100: 59
User entered Value is within the Range (Below 100

Let me enter the Different Value

Please Enter any integer below 100: 987
User entered Value is Outside the Range (Above 100)

In this Python for loop else example, the following statement will ask the user to enter integer number and stores the user entered values in variable number

In the next line we used the for loop with range to iterate

for i in range(0, 100):

Next we used If Statement to check whether the user entered value is within the range (means, number < 100). If the condition is True, the following statement will execute and the Break statement will help to exit from the for loop

 print(" User entered Value is within the Range (Below 100)")
 break

If the user entered value is not within the python range or not (means, number >= 100) then following print statement (within the else block) will be executed

print(" User entered Value is Outside the Range (Above 100)")

Comments are closed.