Loops in Python - Shishir Kant Singh
Loops in Python - Shishir Kant Singh
Like most other languages, Python has for loops, but it differs a bit from other like C or Pascal.
In Python for loop is used to iterate over the items of any sequence including the Python list,
string, tuple etc. The for loop is also used to access elements from a container (for example list,
string, tuple) using built-in function range().
Syntax:
for variable_name in sequence :
statement_1
statement_2
....
Parameter:
Name Description
variable_name It indicates target variable which will set a new value for each iteration of
the loop.
Red
Blue
Green
Black
In the above example color_list is a sequence contains a list of various color names. When the
for loop executed the first item (i.e. Red) is assigned to the variable c. After this, the print
statement will execute and the process will continue until we reach the end of the list.
range(a)
range(a,b)
range(a,b,c)
Syntax:
for <variable> in range(<number>):
Example:
>>> for a in range(4):
print(a)
0
1
2
3
Syntax:
for "variable" in range("start_number", "end_number"):
Example:
>>> for a in range(2,7):
print(a)
2
3
4
5
6
Example:
>>> for a in range(2,19,5):
print(a)
2
7
12
17
>>>
The following example counts the number of even and odd numbers from a
series of numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
count_odd = 0
count_even = 0
for x in numbers:
if x % 2:
count_odd+=1
else:
count_even+=1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
Output:
Number of even numbers:4
Number of odd numbers: 5
In the above example a tuple named numbers is declared which holds the
integers 1 to 9.
The best way to check if a given number is even or odd is to use the modulus
operator (%).
The for loop iterates through the tuple and we test modulus of x % 2 is true or
not, for every item in the tuple and the process will continue until we rich the end
of the tuple.
Finally, we print the number of even and odd numbers through print statements.
In the following example for loop iterates through the list "datalist" and prints
each item and its corresponding Python type.
datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],
{"class":'V', "section":'A'}]
Output:
Type of 1452 is <class 'int'>
Type of 11.23 is <class 'float'>
Type of (1+2j) is <class 'complex'>
Type of True is <class 'bool'>
Type of w3resource is <class 'str'>
Type of (0, -1) is <class 'tuple'>
Type of [5, 12] is <class 'list'>
Type of {'section': 'A', 'class': 'V'} is <class 'dict'>
In the following example for loop iterates through the dictionary "color" through its
keys and prints each key.
>>> color = {"c1": "Red", "c2": "Green", "c3": "Orange"}
print(key)
c2
c1
c3
>>>
print(value)
Green
Red
Orange
>>>
Syntax:
while (expression) :
statement_1
statement_2
....
The while loop runs as long as the expression (condition) evaluates to True and
execute the program block. The condition is checked every time at the beginning
of the loop and the first time when the expression evaluates to False, the loop
stops without executing any remaining statement(s). The following example
prints the digits 0 to 4 as we set the condition x < 5.
x = 0;
print(x)
x += 1
Copy
Output:
0
1
2
3
4
One thing we should remember that a while loop tests its condition before the
body of the loop (block of program statements) is executed. If the initial test
returns false, the body is not executed at all. For example the following code
never prints out anything since before executing the condition evaluates to false.
x = 10;
print(x)
x += 1
Copy
Flowchart:
The following while loop is an infinite loop, using True as the condition:
x = 10;
while (True):
print(x)
x += 1
You can attach an optional else clause with while statement, in this case, syntax
will be -
while (expression) :
statement_1
statement_2
......
else :
statement_3
statement_4
......
The while loop repeatedly tests the expression (condition) and, if it is true,
executes the first block of program statements. The else clause is only executed
when the condition is false it may be the first time it is tested and will not execute
Shishir Kant Singh (http://shishirkant.com)
An Educational and Business Consultant Page 10
if the loop breaks, or if an exception is raised. If a break statement executes in
first program block and terminates the loop then the else clause does not
execute. In the following example, while loop calculates the sum of the integers
from 0 to 9 and after completing the loop, else statement executes.
x = 0;
s = 0
s = s + x
x = x + 1
else :
Output:
The sum of first 9 integers: 45
Flowchart:
s = 0
s = s + x
x = x + 1
if (x == 5):
break
else :
Copy
Output:
The sum of 5 numbers is : 10
In the above example the loop is terminated when x becomes 5. Here we use
break statement to terminate the while loop without completing it, therefore
program control goes to outside the while - else structure and execute the next
print statement.
Syntax:
while (expression1) :
statement_1
statement_2
......
if expression2 :
break
for variable_name in sequence :
statement_1
statement_2
if expression3 :
break
Example: break in for loop
In the following example for loop breaks when the count value is 5. The print
statement after the for loop displays the sum of first 5 elements of the tuple
numbers.
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
num_sum = 0
count = 0
for x in numbers:
count = count + 1
if count == 5:
break
Output:
Sum of first 5 integers is: 15
count = 0
while(count<10):
count = count + 1
if count== 5:
break
Output:
Sum of first 5 integers is : 10
if (x == 3 or x==6):
continue
print(x)
Copy
Output:
0
1
2
4
5
In the above example, the for loop prints all the numbers from 0 to 6 except 3
and 6 as the continue statement returns the control of the loop to the top