For Loop in Python | Syntax, Example

For loop in Python is a basic conditional looping structure that executes a statement or a block of statements a certain number of times.

We use a for loop in the program when we know exactly how many times we have to repeat a loop.

For example, the following code prints “You are the high scorer!” five times.

# Program code to print a statement five times.
for count in range(0, 5):
    print('You are the high scorer!')

In Python programming, the for loop also has the ability to iterate over elements of sequential data types, such as strings, lists, or tuples.

The for keyword loops over all elements present in any list specified to the in keyword.

Syntax of For Loop in Python


Python provides a more concise syntax for creating for loops. The general syntax for using a for loop in a program is as:

for iterating_var in sequence:
    statement(s)

In the above syntax, the for loop starts with for keyword and ends with a colon (:) character. The iterating_var after for keyword is a loop variable that keeps the track of how many times the loop has to run so far.

The block of statements that gets repeated in a loop is called the loop body. It may contain any sequence of Python statement. You must follow the indentation in the body with four spaces from the beginning of the line that begins the for loop.

How does For loop Work in Python?


For loop in Python works like this:

a) The first element in the sequence gets assigned to the iteration variable called iterating_var. After that, the statement block (i.e. loop body) executes.

b) Assigning elements from the sequence to the iterating_var and then executing the statement block continues until all the elements in the sequence execute.

The flowchart diagram of a for loop statement has shown in the below figure.

Flowchart of for loop statement in Python

If the sequence contains an expression list, Python first evaluates it. If it is true, then the Python assigns an element from the sequence to the iterating_var. Next, the block of statement executes.


Let us some example code to understand the basic points of for loop in Python.

Example 1:

# Program to print the statement two times.
for count in 1, 2:
    print('I love to code in Python')
Output:
      I love to code in Python
      I love to code in Python

In this example, Python first assigns the first item 1 from the sequence to the iteration variable count, like count = 1. Then, it executes the statement inside the block of for loop.

Similarly, Python assigns the second item 2 to the iteration variable count, like count = 2, and then again executes the statement inside the for loop body. Thus, the interpreter displays the statement ‘I love to code in Python’ two times on the console.

Example 2:

# Program to print the sequence.
for count in 1, 2, 3, 4:
    print('count = ',count)
Output:
      count =  1
      count =  2
      count =  3
      count =  4

In this example, the loop will repeat four times. Therefore, four values are assigned to the iteration variable count sequentially.

For Loop with range() Function in Python


Python provides a very useful in-built function named range(). It allows us to define a set of numbers over which the ‘for loop’ iterates the numbers in sequential order.

In other words, the range() function produces a sequence of values which can be iterated through using for loop. The general syntax for range() function is as:

range([start], stop [, step])


Here, both start and step arguments are optional and the range of argument values must be an integer value.

start: This argument value indicates the starting of the sequence. If you do not specify the start value, then the sequence of numbers starts from the zero by default.

stop: The stop value produces numbers up to this value, but does not include the number itself. That is, the range of numbers is 0 to n-1. For example, range(1, 4) means the number 1, 2, and 3 but not 4.

step: The step value indicates the difference between every two consecutive numbers in the sequence. It can be both negative and positive, but not zero. However, it is optional.

Let’s take some example program in which we will use for loop statement with range() function.

Example 1:

print('Only stop argument values specified in the range function: ')
for x in range(3):
    print(x)
print('Start and stop argument values specified in the range function: ')
for x in range(2, 5):
    print(x)
print('Start, stop, and step argument values specified in the range function: ')
for x in range(1, 9, 3):
    print(x)
Output:
      Only stop argument values specified in the range function: 
      0
      1
      2
      Start and stop argument values specified in the range function: 
      2
      3
      4
      Start, stop, and step argument values specified in the range function: 
      1
      4
      7

In the above Python code, the function range(3) produces numbers 0, 1, and 2. During the first iteration, Python assigns the value 0 to the iteration variable x and executes the statement inside the for loop block.

This process continues to execute until Python assigns all the numbers generated by the range() function to the variable x. The function range(2, 5) generates a sequence of numbers 2, 3, and 4.

The function range(1, 9, 3) generates a sequence of numbers 1, 4, and 7 with the difference between each number 2.


Example 2:

Let’s write the Python code to calculate the sum of numbers from 1 to 10.

sum = 0
for num in range(1, 11):
    sum = sum + num
print('Sum of numbers between 1 to 10 = ',sum)
Output:
      Sum of numbers between 1 to 10 = 55

For loop with String in Python


Let’s write a Python program to iterate over each character in the string using for loop conditional statement.

for ch in 'Python':
    print('Current character is ',ch)
Output:
      Current character is  P
      Current character is  y
      Current character is  t
      Current character is  h
      Current character is  o
      Current character is  n

In this example, we have created an iteration variable ch that iterates through each character of the string and prints each character in the separate line.

For loop with List in Python


A list is a collection of elements or items. We can use for loop to iterate over the elements of a list. For example, there is a list of fruit items we will iterate it.

fruits = ['Apple', 'Banana', 'Orange', 'Mango']
for item in fruits:
    print(item)
print('Loop finished...')
Output:
      Apple
      Banana
      Orange
      Mango
      Loop finished...

In this example, we have created an iteration variable called item that holds a single item in the list. The value of variable item is updated each time when the loop iterates over the elements of list.

Thus, the variable item holds Apple, Banana, Orange, and finally Mango. Once it reaches at the end of list, the for loop stops.

For loop with a Tuple


Let’s write a Python program to iterate through each item in the tuple using for loop.

color = ('Red', 'Green', 'Blue', 'Orange')
for item in color:
    print(item)
print('Loop finished...')
Output:
      Red
      Green
      Blue
      Orange
      Loop finished...

Else Statement with For loop in Python


Python supports having an else statement associated with a for loop. If we use an else block with a for loop, the else block will execute only if the loop ends normally, not by encountering a break statement.

Consider the following example code in which we have used an else block with for loop that searches for an even number in the given list.

num = [3, 5, 7, 9, 11]
for n in num:
    if n % 2 == 0:
        print('List contains an even number.')
else:
    print('List does not contain any even number.')
Output:
      List does not contain any even number.

As you can see, that else block is executed when the loop has stopped iterating the list. Since there is no any even number in the list, therefore, statement inside the else block executes.

Advanced Example Programs based on For loop


Example 1:

Let’s write a program in Python to calculate the sum of all even and odd numbers up to a number entered by the user.

num = int(input('Enter a number: '))
even = 0
odd = 0
for x in range(num):
    if x % 2 == 0:
        even = even + x
    else:
        odd = odd + x
print('Sum of even numbers = ',even)
print('Sum of odd numbers = ',odd)
Output:
      Enter a number: 10
      Sum of even numbers =  20
      Sum of odd numbers =  25

In this example, we have generated a range of numbers using range() function. We have used the modulus operator to check even or odd numbers.

Then, we added up all even numbers and assigned to the variable even. Similarly, we added up all odd numbers and assigned to the variable odd. Then, we printed the result on the console.


Example 2:

Let’s write a program in Python to find the factorial of a number entered by the user.

# Python program to find the factorial of a number.
num = int(input('Enter a number: '))
fact = 1
if num < 0:
    print('Please enter a positive number because factorial does not exist for negative number.')
elif num == 0:
    print('The factorial of 0 is 1.')
else:
    for x in range(1, num + 1):
        fact = fact * x
print('The factorial of number', num,'=', fact)
Output:
      Enter a number: 6
      The factorial of number 6 = 720

The factorial of a positive integer number n is denoted by n! which is the product of all positive integers less than or equal to n. i.e. n! = n * (n – 1) * (n – 2) * (n – 3) . . . 3 * 2 * 1. For example, 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720. The factorial of 0! is always 1.

In the above code, first we have used the input() function to take a number from the user. Then, we have cast the entered number to int and stored it into a variable num.

We have assigned the value 1 to the variable fact. To find the factorial of a number, we need to check the entered number is positive or negative.

If the user enters a zero, then the factorial of zero is always 1. We have used the range() function to produce to numbers from 1 to the user entered number.

Every number will be multiplied by the fact variable and is assigned to the fact variable itself within the for loop. The for loop will iterate over all numbers starting from 1 to the user entered number. At last, the final factorial value is printed on the console.


Example 3:

Let’s write a program in Python to print a list of numbers in reverse order using for loop.

# Python program to print a list of numbers in reverse order.
nlist = [2, 4, 6, 8, 10, 12]
print('List of original numbers: ')
for x in nlist:
    print(x, end= ' ')
num = len(nlist) # Here, function len() returns the number of items in the container.
i = 0
j = -1
print('\nList of numbers in reverse order: ')
while i <= num - 1:
    print(nlist[j], end=' ')
    j -= 1
    i += 1
Output:
      List of original numbers: 
      2 4 6 8 10 12 
      List of numbers in reverse order: 
      12 10 8 6 4 2 

In this tutorial, you have learned about another basic for loop structure in Python with various example programs. Hope that you will have understood the basic points of for loop statement and practiced all example programs.
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love