Loops are used in every programming language to allow the possibility of repeating a specific section of the code for a specific amount of times or until some condition is met. They can also be used to iterate collections of data like lists, tuples, strings and so on.
Python has two types of loop: the for
loop and the while
loop. This section describes the first while the second will be described in the section below.
The syntax of the for loop uses the keyword for
, the main object that needs to be iterated and the variable that will be assigned the content of the object, these below are some examples.
#This code prints the numbers from 0 to 9 for i in range(10): # range(10) provides integers from 0 to 9 print(i) # i is printed at every loop #This code prints all the elements of the list l1=["a","b","c"] for i in l1: # l1 is the list and i is assigned every element of this list print(i) # prints the elements of the list #This code prints the characters of a string s1="hello" for i in s1: # the string s1 is seen as a collection of characters print(i) # prints the characters of the string
The command break
is used in the loop to go out of the loop before the loop is finished. Typically this is used when a specific condition is met and continuing the loop is not useful anymore. For example, in the code below we try to find the index of the element equal to 0. This is not the best way of doing this but as an example we can see that, once the value has been found, there is no reason to continue the loop.
l1=[2,4,0,1,5,20] # List with one value equal to 0 index=0 # The index starts from 0, which is the first element checked for i in l1: # The loop iterates the list if(i==0): # If the specific value i is equal to 0 then ... break # ...exit the loop with break index+=1 # If still in the loop increase the index by 1 and check again print(index) # The index printed is 2
The command continue
is used to skip the current iteration and continue with the next. This can be used when the code in the loop needs to be executed only on particular elements of the collection of data and the rest is skipped. For example, we can rewrite the code used before to check if an element is not 0, if that is the case it needs to be skipped otherwise the index needs to be printed. The result is the same.
l1=[2,4,0,1,5,20] # List with one value equal to 0 index=-1 # The index starts from -1 given that at the beginning of the loop is increased by 1 for i in l1: # The loop iterates the list index+=1 # index is increased by 1 if(i!=0): # If the specific value i is different from 0 then ... continue # ...do not execute the code below and go to the next print(index) # If this code is executed it means that the value has been found and the index printed is 2
The command else
can be used in the for loop to specify some code that needs to be run once the for loop is finished. If the command break
is used in the code then the code related to the else
is not executed.
#Else code executed for i in range(3): #The loop prints elements from 0 to 2 and the "end" print(i) else: print("end") #Else code not executed for i in range(3): #The loop prints only the element 0 if(i==1): break print(i) else: print("end")
The function range()
used in previous examples begins with 0 and increments by 1 as default, however if different integer values are provided it can start with a specific value, increment with another specific value and then end to a specific value.
for i in range(2,10): #The loop prints values from 2 to 9 print(i) for i in range(3,10,2): #The loop prints values 3,5,7,9 print(i)
It is also possible to use loops within other loops where, for each iteration of the external loop, the full internal loop is executed. However, it is not possible to use the same iterating variable otherwise it is overwritten by one of the loops.
l1=["A","B","C"] l2=[1,2,3] for i in l1: #For each printed element of l1, all elements of l2 are printed print(i) for j in l2: print(j) l3="hello" for i in l1: #For each printed element of l1, all elements of l2 are printed print(i) #However, for each element of l2, all characters of l3 are printed for j in l2: print(j) for k in l3: print(k)
This concludes the introduction of For Loop in Python, try to code it with the online Python console. The section below introduces the While Loop.
The while loop is used to execute a part of code until a specific condition is true. The syntax of the for loop uses the keyword while
and the main condition that needs to be true, these below are some examples.
#This code prints the numbers from 0 to 9 i=0 while(i < 10): print(i) i+=1 # Remember to increase the index, otherwise the loop never ends #This code prints all the elements of the list l1=["a","b","c"] length=len(l1) # Number of elements in l1 i=0 while(i < length): # Differently from for loop, here i is the index and not the value print(l1[i]) # prints the elements of the list (in this case is not i but l1[i]) i+=1 # Remember to increase the index, otherwise the loop never ends
The command break
can used like the case of the for loop to go out of the loop before the loop is finished. Typically this is used when a specific condition is met and continuing the loop is not useful anymore. Using the same example of above, in the code below we try to find the index of the element equal to 0. This is not the best way of doing this but as an example we can see that, once the value has been found, there is no reason to continue the loop. It is interesting to notice that the while loop checks a specific condition, so if in this example we check the elements of the list then we do not need the command break
as shown in the second example.
l1=[2,4,0,1,5,20] # List with one value equal to 0 index=0 # The index starts from 0, which is the first element checked length=len(l1) # Length of l1 while(index < length): if(l1[index]==0): # If the specific value l1[index] is equal to 0 then ... break # ...exit the loop with break index+=1 # If still in the loop increase the index by 1 and check again print(index) # The index printed is 2 #Another way of doing it by taking advantage of the condition that needs to be checked in the loop while(l1[index] != 0): # The condition is met until the value is different from 0 index+=1 # Index updated every time that the condition is met print(index) # The index printed is 2
The command continue
is used, like the for loop, to skip the current iteration and continue with the next. This can be used when the code in the loop needs to be executed only on particular elements of the collection of data and the rest is skipped. The code below only prints the indexes of the spaces.
s1="This is a text" length=len(s1) index=0 while(index < length): if(s1[index]!=' '): # If the specific character is different from the space then ... index+=1 # ...increase the index by 1 and... continue # ...do not execute the code below and go to the next print(index) # If this code is executed it means that the character has been found index+=1 # Increase the index by 1 otherwise one a space is found the index never increases
The command else
can be used in the while loop to specify some code that needs to be run once the condition is not met anymore. If the command break
is used in the code then the code related to the else
is not executed.
#Else code executed l1=[1,2,3] i=0 length=len(l1) while(i < length): #The loop prints elements of the list 1 to 3 and the "end" print(l1[i]) i=i+1 # Another way to increase a variable by 1 else: print("end") #Else code not executed l1=[1,2,3] i=0 length=len(l1) while(i < length): #The loop prints elements only the first element of the list if(i==1): break print(l1[i]) i=i+1 # Another way to increase a variable by 1 else: print("end")
Also for while loops it is also possible to use loops within other loops where, for each iteration of the external loop, the full internal loop is executed. Also in this case, it is not possible to use the same iterating variable otherwise it is overwritten by one of the loops.
l1=["A","B","C"] l2=[1,2,3] i=0 #index for l1 j=0 #index for l2 len1=len(l1) len2=len(l2) while(i < len1): #For each printed element of l1, all elements of l2 are printed print(l1[i]) i+=1 j=0 # The index of l2 needs to start again from 0 at every loop of l1 while(j < len2): print(l2[j]) j+=1
This concludes the introduction of Loops in Python, try to code them with the online Python console below.