Welcome back to another exciting tutorial on “Python loops and iterations”. In this Python tutorial, you’ll learn the the syntax and use of python for loop and python while loop.
You’ll also learn how and when to use a specific loop with the help of examples. In the end, you will learn about break and continue statement. Let’s begin our tutorial with an introduction to the Python Loops.
If you aren’t following along, I would recommend you to go back where you left or start from here.
In computer programming, we lay stress on DRY i.e. Don’t repeat yourself. We achieve this goal using functions and loops . A python loop is used to execute a section of code many times . This is done by iterating over a list,dictionary,tuple or any other sequence.
This process of repeated execution is controlled using a terminating condition .
A loop should have a terminating condition else it become infinite and halt the program.
There are two categories of python loops :- for-else and while-else loop.
Let me give you an python loop example to help you understand why someone use python loop. Suppose you have to Print numbers from 1 to 4. There will be two approach :-
# Case 1 (Python Loop Example.)
>>> print(1)
1
>>> print(2)
2
>>> print(3)
3
>>> print(4)
4
# Case 2
>>> for i in range(1,5):
... print(i)
...
1
2
3
4
You can see that the answer in both the case is same but the later code is highly optimized and concise. Also, a short code is easy to debug and python loops for sure save many lines of code.
for loop in python iterate over a given sequence like list,tuple,set,string etc.
The loop last when the iterating variable reach at the end of sequence.The code under python for loop is indented.
For loop is used when you have to access every element of a sequence.
Flow Chart of for loop
Syntax
for var in sequence:
Statements under for loop
Example#1 – Write a program to print all the item in a list.
>>> l1 = ['Knowledge','is','Inspiration']
>>> for i in l1:
... print(i)
...
Knowledge
is
Inspiration
Example#2 – Write a program to calculate sum of all numbers in a list.
>>> l1 = [3,4,2,5,6,8,22,4]
>>> sum1 = 0
>>> for num in l1:
... sum1+=num
>>> print(sum1)
54
while loop in python is used to repeat a section of code until a given condition evaluates to true.
It contains an initial condition , a modification statement and a terminating condition.
while loop is an entry controlled loop i.e. body of loop executes only when condition is true.
while loop is used when we do not know the number of times to iterate beforehand.
Flow Chart of while loop
Syntax
while expression_is_true:
Statements under while loop
Example#– Print all numbers before a given number in a list.
>>> l1 = [2,3,4,2,3,1,2,2]
>>> key = 1
>>> i = 0 # initial condition
>>> while l1[i] != key and i<len(l1): # do till the condition is True
... print(i)
... i+=1 # modification statement
...
2
3
4
2
3
Like in C or C++, python also allows you to use loop within loop i.e. for loop in while loop or vice versa.
Syntax
The syntax for nested for loops :-
for var1 in sequence1:
for var2 in sequence2:
Statements to execute
Statements to execute
The syntax for nested while loops:-
while expression 1:
while expression 2:
Statements to execute
Statements to execute
Example#1 – Write a program to traverse a 2D matrix using nested for loops.
>>> l1 = [[1,1,0],[1,0,1],[0,0,1]]
>>> for i in l1:
... for j in l1:
... print(j,end = ' ')
... print('')
...
1 1 0
1 0 1
0 0 1
In the outer loop , i variable refer to every nested list and variable j refer to every element in list i.
Example#2 – Write a program to print the ‘*’ x times where x is an integer element is a list.
>>> l1 = [1,2,3,4,5,6]
>>> l = len(l1)
>>> i = 0
>>> while i0)
... print('*')
... x-=1
... print('')
... i+=1
...
*
**
***
****
*****
******
Outer while loop traverse the list and inner while loop prints ‘*’ .
range() function takes three arguments . It generates an arithmetic progression.
beg – First number of the range (default value is 0).
end – The end is exclusive in the range (end – 1 is the last number).
step – Difference b/w successive terms (default value is 1).
range object does lazy evaluation i.e. it stores the beg,end and step and generates the next number in when needed.
Yet, you can output the whole sequence at once using list ().
Example#1 :- Print all multiples of 3 under 10.
>>> for i in range(3,10,3):
... print(i)
...
3
6
9
Example#2 :- Passing negative step
>>> for i in range(100,10,-20):
... print(i)
...
100
80
60
40
20
Example#3 – Printing sequence at once.
>>> print(list(range(7))
[0, 1, 2, 3, 4, 5, 6]
>>> print(list(range(5,11))
[6, 7, 8, 9, 10]
>>> print(list(range(10,1,-2)))
[10, 8, 6, 4, 2]
Break
break statement is used to end the current python loop. It can be used with both for and while loops.
In case of nested loops, the break statement ends that loop in which it is used and start execution of program from next instruction.
Syntax: –
break
Flow Chart
Example :- Write a program to find if an element is present in a list or not.
>>> key = 6
>>> l1 = [1,2,3,4,5,6,7,8,9,10]
>>> yes = false
>>> for i in l1:
... if i == key:
... yes = True
... break
...
>>> if yes:
... print("Found")
... else:
... print('Not found')
...
Found
In the above example, as soon as the key is found (key == i becomes true) ,the break statement executes and loop ends there.
Continue
continue statement when execute returns the control to the beginning of the python loop. It rejects the remaining section of code for that iteration.
continue statement can be used with for and while loop.
Syntax: –
continue
Flow Chart
Example :- Write a program to print all the numbers in a list except the given key.
>>> l1 = [1,2,3,4,5,6,7]
>>> key = 5
>>> for i in l1:
... if i == key:
... continue
... print(i)
...
1
2
3
4
6
7
In above example, the continue statement executes when i == 5 so the remaining code i.e
print(i) doesn’t executes for i == 5 iteration.
Pass
pass statement is used to indicate a null code block. A python loop with only pass statement do nothing and is also syntactically correct.
If we don’t know the section of code at that time but will be knowing in future , pass statement is used .
Syntax: –
pass
Example :-
>>> for i in range(1,10):
... pass
...
Else clause is executed whenever a python loop terminates after exhaustion of iterative object (for loop) or condition becomes false(while loop).
When break statement executes within loop,else clause doesn’t execute.
Syntax
for var in sequence:
Statements to execute
else:
Statements to execute
while expression:
Statements to execute
else:
Statement to execute
Flow Chart
Example# – Write a program to check whether a number is in the list or not.
>>> key = 11
>>> l1 = [1,2,3,4,5,6,7,8,9,10]
>>> for i in l1:
... if i == key:
... print('Found')
... break
... else:
... print('Not found')
...
Not found
In the above example, the key (11) is not in the list. The break statement never executes and the for loop ends naturally so the else block executes.
Example# – Write a program to check a number is prime or not.
>>> n = 15
>>> i = 2
>>> while i<n/2+1:
... if n%i == 0:
... print('This is not a prime number')
... break
... i+=1
... else:
... print('Whooo..It is a prime number')
...
This is not a prime number
In above example, 15 is divisible by 3 so it is not a prime number. Hence, break statement executes and code under else clause is ignored.