Python For Loop

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

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 syntax, the Object may be anything you want to iterate. For Example, String or Lists and so on.

  • The compiler starts with Object means, Python for loop will iterating object and then it will assign the first value to an item. For example, our object is a string and the text is Tutorial, the compiler will assign T to the item
  • Next, it will execute the statements inside the iterator.
  • After completing the statements, the compiler will go to the Object and assign the next value to the item
  • The process repeats until there are no items in the Objects.

Python For Loop Flow Chart

The flow chart of For Loop

FOR LOOP FLOW CHART

The execution process of the for loop in python is:

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

Python For Loop Example

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

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

# List Example
Countries = ['India', 'U K', 'U S A', 'Australia']
for Country in Countries: # Second one
    print("Countries are: ", Country)
    
print("---This is Outside List")
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---

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

First, we declared a string variable called Str and assigned the text “TutorialGateway”

Next, we used the Python for loop to iterate over a sequence of individual characters in the string and display them.

Then we used two print statements outside the iterator. These statements will be executed once the compiler exit from first block.

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

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

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

Next, we used the python for loop to iterate through the Countries List and display the individual list items.

Then we used print statement outside block of code. This statement will be executed once the compiler exit from second.

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

It is too big to explain the first one. 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 in the second one.

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

Analyzing the code in iteration wise

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

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

Third – Country = ‘U S A’. It prints the statement inside.

Fourth – Country = ‘Australia’. It executes statement inside it.

Fifth: There will be no items in the object to assign to Country variable so, the compiler will exit from it.

For Loop range object Example

The syntax of the Python For Loop range function is

for item in range(Start, End, Steps):
     Statement1
     Statement2
     ………
     StatementN

The Python for loop range has three arguments:

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

range with two arguments

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

for number in range(0, 5):
    print("Current Number: ", number)
Current Number: 0
Current Number: 1
Current Number: 2
Current Number: 3
Current Number: 4

First Iteration – number in range(0, 5)

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

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

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

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

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

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

For Loop range with three arguments

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

for number in range(9, 14):
    print(number)
print("")

print("Second One")
for num in range(5, 18, 2):
    print(num)

range with three arguments output

9
10
11
12
13

Second One
5
7
9
11
13
15
17

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

Use For Loop range on String and Lists

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

Str = "Program"
for word in range(len(Str)):
    print("Letters at index {0} is = {1}".format(word, Str[word]))
  
print("\n----This is Outside String---")
print()

# 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 example, First, we declared the String variable and assigned the text.

In the next line we used the range function. If you observe the below code, we used the len function inside the python range function to calculate the string length. It means, above range code can also be written as

for word in range(len('Program'))  # Where 7 is the length of Str

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

Python For Loop Else

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

  • If there are items in Sequence then statements in it will execute.
  • If there are no items in Sequence then statements inside the Else block will be executed. If we used Break statement to break it then Else block will not executed.
  • If it finds the continue statement, it skips the current number and prints the remaining values.

Else Statement

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 statement

Python For Loop Else Example

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

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)")
Please Enter any integer below 100: 59
User entered Value is within the Range (Below 100

Let me enter the Different Value for the above example.

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

In this for loop else example, the first line 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

Next we used If condition to check whether the user entered value is within the range (means, number < 100). If the condition is True, if block code will run and the break statement will help to exit from it.

If the user entered value is not within the Python For Loop range or not (means, number >= 100) then else block print the code (within the else code block) will print.

Comments are closed.