for loops - I





Hello folks....!!!!

Today we will look into for-loops in Python.

for-Loop in C/C++ :

In C/C++, we declare for loops in the following syntax:
                        for(initialization;condition;incrementation)
                        {
                                   statement 1;
                                   statement 2;
                        }


In python it slightly differs. We use range() function to check condition. The syntax is as follows :
                        for variable_name in range(0,n):
                                            statement 1
                                            statement 2
  • Here the range(x,y) keeps track of number of times the loop has to execute. In python for loops can be used to indicate each item in an iterable. Iterables are nothing but lists, dictionaries, tuples and sets.
  • The indentation plays the major role. It specifies which statements are under loop's control
  • The loop is executed y-1 times. It starts from x and remains true until y-1.

Example 1 :

Look at the code below, which just prints the number from 1 to 10:

Python for loop

Here the loop control variable is 'i' which is first initialized to the value '1', and the loop will be executed until the value of i reaches (11-1). The incrementation is done automatically. By default the loop variable will be incremented by 1. 

Example 2 :

Now what should we do if we wish increment by 2 steps or any other number of steps. Look at the code snippet below:


In the range() method we add another parameter at the end which denotes the number of steps to increment. Here I have incremented it 2 steps, so that only the odd numbers get printed.

Example 3:

Now let us write a decrementing loop. We will print the even numbers from 1 to 10 in reverse order.


Python allows to iterate through the data structures like lists,strings until all elements are iterated through.

Example 4: Strings


  • Here, the loop control variable is 'char'. This loop iterates through each character in the given string and prints it.
  • It is not mandatory that the loop control variable should be 'char', it can be any valid variable name like 'i' or 'c' or anything.
  • The loop is executed until there are characters left in the string.
  • This will be useful in String problems in placements.

Example 5: Lists


  • Here 'i' is the loop control variable. It denotes each element in the list.
  • It iterates through the list until all elements are processed.
  • Incrementation part is not required here. At each step the next element is considered.

Example 6: Dictionary


  • Here the loop control variable is 'k' which denotes the keys in the dictionary.
  • The loop is executed until there are no keys left in the dictionary.


Next Topic👉

Comments