Python Programming - Python Loops

Python Programming – Python Loops

In the previous sections, we have discussed decision-making statements that control the flow either sequentially or skip some statements depending upon the test condition. In some situations such as computing the table of a number, it is required to repeat some set of statements to attain the required results. This repetition can be achieved by using a loop control structure. In this section, we will discuss various loops provided by the Python language. We will demonstrate how loops are supportive and effective in the Python language.

Types of loops

The repetition of a loop can also be termed as iteration, which means repetitive execution of the same set of instructions for a given number of times or until a particular result is obtained. The repetition of a loop is controlled by a test expression (condition) specified with the loop. The loop begins and continues its execution as long as the test expression evaluates to true. The loop terminates when the conditional expression evaluates to false. After that, the control transfers to the next statement that follows the loop. The Python language supports 2 types of iterative or looping statements while and for as displayed in Table 4.2.

Loop Description
While It iterates a statement or group of statements while a given condition evaluates to true. It evaluates the test expression before executing the loop body.
for It executes a sequence of statements multiple times until the test expression evaluates to true.
Nested loop A loop either while or for, inside another loop is called nesting of the loop.

Python while Loop

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. It is also called a preset loop that is used when it is not predetermined how many times the loop will be iterated. The syntax of the while loop is given as follows:

while test condition:
body of loop

In a while loop, initially, the test expression is evaluated. If the test expression evaluates to true only then the body of the loop is executed. After one iteration, the test expression is evaluated and tested again for true or false. This process continues until the test_expression evaluates to false. On the other hand, if the test_expression evaluates to false at the first time, the body of the loop will not be executed at all and the first statement after the while loop will be executed.

Python Programming - Python Loops chapter 3 img 1

Indentation determines the body of the while loop in Python. The body starts with indentation and the first unindented line marks the end of the loop. The flow chart of the while loop is given in Fig. 4.4.

Code 4.7. Illustrates a simple program to display counting from 1 to 10 using a while loop. In the program, it can be seen that the count variable is initialized to 1 and the test expression count<=10 evaluates to true as 1<=10. Thus, the body of the loop begins execution and prints the value of the count variable as 1. The count variable is incremented by 1 and becomes count=2. Then, control goes back to the test expression count<=10, that is 2<=10, which is true again, and the body of while loop executed again and so on. The loop will continue to execute until the value of count becomes 11 and test expression 11 <=10 evaluates to false. Eventually, we obtain the desired output.

Code: 4.7. Illustrates the use of while loop to print counting from 1 to 10,

# Program to display counting 1 to 10 by using while loop
count=l
while(count<= 10):
print(count)
count=count+1
print(‘Outside while loop’)
Output
1
2
3
4
5
6
7
8
9
10

Outside while loop

Another example of while is illustrated in Code 4.8. The program computes the factorial of the number input by the user. We ask the user to enter a number, n. while loop is used to compute the factorial of number n. The condition will be true as long as our counter variable i is less than or equal to n. We need to increase the value of the counter variable in the body of the loop. This is an essential part and cannot be skipped. Undoing so will result in an infinite loop (never-ending loop). Finally, the result is displayed.

Code: 4.8. Illustration of while loop to compute factorial of a number.

# This program computes the factorial of a number input by the user
n = input(‘Enter n:’)
n= int(n)
i=1
fact=1
while(i<=n)
fact=fact*i
i=i+1
print(‘The factorial is:’, fact)
Output 1

Enter n: 5
The factorial is: 120

Output 2

Enter n: 9
The factorial is: 362880

Note:
The test condition and test expression can be used interchangeably as both these terms refer to a similar meaning.

The Infinite Loop

A loop becomes an infinite loop if a condition never becomes FALSE. The programmer must be cautious when using while loops because of the possibility that the test_condition never evaluates to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop. The programming example of an infinite loop is given in Code: 4.9. In this example since n=5, the test-condition n>0 inside while remains true, and therefore, the message “n is always positive” is displayed indefinite times. In such cases, the program is terminated by pressing ctrl+c altogether.

Code: 4.9. Illustration of the infinite while loop.

#infmite while loop illustration

n=5
while (n>0):
print(‘n is always positive’)
print(‘this message will be never displayed’)

Output

n is always positive
n is always positive
n is always positive
n is always positive
. . .

Note:
An infinite loop can be advantageous in client/server programming, where the server needs to run constantly, in order to make clients communicate with it.

Using else Statement with while Loop

The Python language provides a new feature, which is not available in C/C++/Java. Alike else statement with if, it can be used with the loop construct also. If the else statement is used with a while loop, the else statement is executed when the test expression evaluates to false. The following example in Code 4.10. illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise else statement gets executed. We can see from the illustration
that as long as the test condition n>0 is true the statements associated with while get executed and print the value of n as 5,4,3, 2, 1. But, when the condition n>0 becomes false then else part gets executed and the message is displayed as “The value of n is zero”.

Code: 4.10, Illustration of use of else with while loop.

# program to illustrate the use of else with while

n=5
while (n>0):
print(n)
n=n-1

else:
print(‘The value of n is zero’)

Output

5
4
3
2
1

The value of n is zero

Python for Loop

In Python, alike while, the for loop is used to iterate over a set of statements. However, the for loop iterates over a sequence of number represented by list, tuple, string, or other sequential objects. Iterating over a sequence is also called traversing. The syntax of for loop is given as follows:

for val in sequence:
statement(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the counter variable val. Next, the statements block is executed. Each item in the list is assigned to val, and the statement(s) block is executed until the entire sequence is drained out. Indentation is used to separate the body of for loop from the rest of the code. The flow diagram of for loop is given in Fig. 4.5.

Python Programming - Python Loops chapter 3 img 2

The programming example of for loop is presented in Code. 4.11. The program displays the elements of a list using for loop. Another example of for loop is given in Code 4.12., where the string values are accessed using for loop. In this program, four cities are displayed. Here, the counter variable is a city, which displays the values in sequence ‘cities’, until the entire sequence is exhausted by for loop. One can also access the individual characters of string using for loop, which is also illustrated in the program Code 4.12., where the individual characters of PROGRAM string are displayed.

Code: 4.11. Program to display the content of marks list by using for loop.

# This program displays the contents of a list by using for loop
marks = [56, 43, 65, 42, 73, 51, 24 ]
for i in marks:
print(i)
Output

56
43
65
42
73
51
24

Code: 4,12. Program to display cities using for loop.

# Program to display the string values using for loop

cities = [“Delhi”, “Mumbai”, “Chennai”, “Kolkata”]
for the city in cities:
print(‘Current city:’, city)
for c in “PROGRAM”:
print(c)

Output

Current city: Delhi
Current city: Mumbai
Current city: Chennai
Current city: Kolkata

P
R
O
G
R
A
M

The range ( ) Function

The range () function is quite useful in the Python programming language. It is used to generate a sequence of numbers. Most commonly, it is used with, the for loop and it generates lists of arithmetic progression. The range() function can hold three arguments, start, stop and step size as range(start,stop,step size). The step size defaults to 1 if not provided. This function would be inefficient if it stores all the values in memory. So it remembers the start, stop, step size and generates the next number on the go. In the above one argument is compulsory and the other two are optional as described below:

• range(12) : it will generate numbers from 0 to 11 (12 numbers). That means it generates a number up to but excluding the last number in the specified range. By default, it starts from 0 and goes up to one less than the specified number as shown in the example given in Code: 4.13. This argument is compulsory.

• range(2, 12): in this, the sequence of numbers to be displayed starts from 2 and ends at 11. That is the first argument represents the beginning number and the second argument represents the total range. To specify the first argument is optional as by default range ( ) function starts from sequence 0.

• range(2, 20, 2): in this, the third argument represents the step size which is 2, which is to be added to the current number to generate the next number in sequence up to 20. To specify the step size is also optional as by default the step size is 1 in range() function.

To illustrate the use of range() function, it is used with the list() function as shown in Code: 4.13. (interactive mode)
Code: 4.13, Illustration of rangeQ function.

>>> range(12)
range(0,12)
>>> list(range(12))
[0, 1,2, 3,4, 5, 6, 7, 8, 9, 10, 11]
>>> list(ratfge(2,12))
[2,3,4, 5,6,7, 8, 9, 10, 11]
>>> list(range(2, 20, 2))
[2, 4, 6, 8, 10, 12, 14, 16, 18]

The alcove statements are written directly on the Python prompt. The first statement represents the range that varies from 0 to 12. The second statement lists the values in the range(12) by using the list() method. If we specify the upper bound and lower bound in the range function then the list() method displays the values within that range as shown in the third statement. The fourth statement represents three arguments of range() method i.e., start, stop, and step size and the list method display the output as per the values provided in these three arguments.

The range() function can be used with for loop to iterate through a sequence of numbers. By accompanying with len ( ) function, the range() function is used to iterate through a sequence using indexing as shown in Code:4.14.

Code: 4.14. Program to illustrate the use of range function in for loop.

# Program to iterate
# through a list
# using indexing# List of language
language=[‘Python’,’Java’,’C++’]# iterate over the list using index
for i in range(len(language)):
print(“I like”, language[i])
Output

I like Python
I like Java
I like C++

for Loop with else

Alike while loop, a for loop can work with an optional else block as ” well. The else part gets control of the interpreter if all the elements in the sequence used in for loop drained out. Alike C/C++ statements if the break statement is used in Python to stop a for loop then else part gets ignored. Hence, a for loop’s else part runs only if no break encounters. The program to search an element from a list of numbers is given as an example of this concept in Code: 4.15.

Code: 4.15. Program to illustrate the use of else with for loop.

# Program to show
# the control flow
# when using else block
# in a for loop# a list of numbers
list_of_numbers=[10, 20, 30, 40, 50, 60, 70]# take input from user
input_number=int(input(“Enter a number: “))# search the input digit in our list
for i in list_of_numbers:
if input_number== i:
print(“Number is in the list”)
break
else:
print(“Number not found in the list”)
Output 1

Enter a digit: 50
Number is in the list

Output 2
Enter a digit: 100
Number not found in the list

Here, we have a list of numbers. We ask the user to enter a number and check if the number is on our list or not. If the number is present, for loop breaks with a message that the number is in the list. So, the else part does not get executed. But if all the items in our list drain out then the message Number not found in the list gets printed when the program enters the else part.

Nested Loops

Python programming language allows using one loop inside another loop. The following section shows a few examples to illustrate the concept. The syntax of nested for loop is as under

for val in sequence:
for val in sequence:
statement(s)
statement(s)

The syntax for a nested while loop statement in the Python programming language is as follows –

while test_condition:
while test_condition:
statement(s)
statement(s)

An advantage of nesting of loops is that we can put any type of loop inside any other type of loop. For example, a for loop can be put inside a while loop or vice versa. The program Code: 4.16. computes factorials of first n natural numbers using nested for loops.

Code: 4.16. Program to illustrate nested loops.

# This program computes the factorial of first n natural numbers, where the value of n is input by the user.

n = input(‘Enter a number:’) n= int(n)
for i in range(1,n+1): ;
f=l
for j in range(l, i+1):
f=f*j
print (‘factorial of {0} is {l}’.format(i, f))
print(‘end of loop’)

Output
Enter a number: 8
factorial of 1 is 1
factorial of 2 is 2
factorial of 3 is 6
factorial of 4 is 24
factorial of 5 is 120
factorial of 6 is 720
factorial of 7 is 5040
factorial of 8 is 40320
end of loop

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *