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 before getting into the details:

Python For Loop Syntax

The syntax of the For Loop 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, the for loop will iterate the object and then assign the first value to an item. For example, if 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 the For Loop

FLOW CHART

The execution process of the for loop is:

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

Python For Loop Example

Use this example to extract individual words from strings and the list’s data.

# Example
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 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 the first block.

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

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

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 statements outside the block of code. This statement will be executed once the compiler exit from the 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 for loop code iteration wise

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

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

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

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

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

range object Example

The syntax of the Python For Loop range function is

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

The 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 the 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 for loop range program will display the sequence of numbers from 0 to 4.

# Example
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, the program will be terminated.

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)

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 displays numbers from 9 to 13. Whereas, in the second, we used the step value as 2, the second displays alternative numbers from 5 to 18.

Use Python For Loop range on String and Lists

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

# on String and Lists Example
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 the 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 also allows us to use the else statement with For loop statements and 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 the Break statement to break it, then the Else block will not execute.
  • 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 the compiler will run the inside statements. Otherwise, the 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 Values 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 an integer number and store the user entered values in a variable number. In the next line, we used the for loop with range to iterate

Next, we used the If condition to check whether the user entered value is within the range (means, number < 100). If the condition is True, the 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.