In This Tutorial:
The for loop, also known as iteration statement is generally used when you know the number of iterations in the loop.This type of loop (a for loop) will iterate over a given sequence, as follow:
for loop_variable in sequence:
statements(s) to be executed
The flow of the for loop is:
- First of all, if the sequence has a list, for example, numbers (1,2,3,4..) the first number will be assigned to the loop_variable.
- After evaluation, the block of statements will be executed and the execution will be moved to next item of the list in sequence. The process will go on until all items are entertained.
- The statements to be executed must be at the same indentation.
- If the second statement is not at same indentation or written at the root (without any space) it will be treated outside of the for loop.
- In other programming languages like Java, C#, we generally use curly braces to enclose the block of statements to be executed in the for loop.
A for loop example with number sequence
Following is a simple example of using the for loop Python. A sequence of numbers is created and used in the for loop. As such, four number sequence is assigned, the iteration will occur four times that will display the current value of variable j.
i = [1,2,3,4]
for j in i:
So what happened in the loop? First of all, a sequence of numbers, i is created. Then a loop variable, j is used in the for loop. A print statement is placed to display the current number in the sequence, with four-space indentation.
As the loop executed, the first number in the sequence will be assigned to loop variable j and then it will be displayed on the screen. The same will happen to the rest of the numbers in sequence and finally, the control will be moved out of the for loop to the next line of code.
For loop example with string characters
The following for loop example uses the string sequence rather than the numbers for demonstration purpose.
i = ['a','b','c','d']
for j in i:
As you can see, we have created a sequence of four characters which is assigned to the variable i. After that, a for loop is used to display those characters by using the print statement.
For loop example with words
Not only you can use single character or numbers as a sequence, you can use the words as a sequence in Python for loops. See example below:
words = ['This','is','Python','For', 'Loop','Example']
for j in words:
Output will be
Using loop control statements
Loops can be controlled by using the loop control statements. Following are the control statements supported in Python. Click on any for its detailed chapter with examples.
- Python Break
- Python Continue
- Pass statement
Further reading: The While loop in Python