Thursday, October 4, 2018

Control Structures in Python (Loops in Python)

Computer programs are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that programs do well and people do poorly. Because iteration is so common, Python provides several language features to make it easier. One form of iteration in Python is the while statement. The other is for statement.

There might be a situation where you might require to run a single block of code a number of times, in that situation, loops come in handy. Loops come handy in situations such as iterating through data structures in any programming language or traversing through large sets of data to filter out junk data, followed by certain keywords followed by alphanumeric characters followed by certain special characters.

Types of loops

There are two types of loops, namely:

1. Definite: In this case, the code of block runs for a defined number of times. This is useful when the programmer exactly knows in how many counts the task will be executed or let's assume that he knows the number of elements inside the data structure. For example, the strength of a classroom.

2. Indefinite: In this case, the code of block runs until the condition is true. This is useful where the count is unknown. For example, trying to figure out the number of times Hyderabad appears in a literary article.

While Loop

A while loop repeatedly executes instructions inside the loop while a certain condition remains valid. The structure of a while statement is as follows:

while condition is true:

do this


Usually when using a while loop, we need to first declare a variable to function as a loop counter. Let’s just call this variable counter. The condition in the while statement will evaluate the value of counter to determine if it smaller (or greater) than a certain value. If it is, the loop will be executed.

Example- while_loop.py

counter = 5
while counter > 0:
         print ("Counter = ", counter)
         counter = counter - 1




One has to be careful when using while loops due to the danger of infinite loops. Notice that in the program above, we have the line counter = counter - 1? This line is crucial. It decreases the value of counter by 1 and assigns this new value back to counter, overwriting the original value.

We need to decrease the value of counter by 1 so that the loop condition while counter > 0 will eventually evaluate to False. If we forget to do that, the loop will keep running endlessly resulting in an infinite loop. If you want to experience this first hand, just delete the line counter = counter - 1 and try running the program again.

The program will keep printing counter = 5 until you somehow kill the program. Not a pleasant experience especially if you have a large program and you have no idea which code segment is causing the infinite loop.

For Loop

The for loop executes a block of code repeatedly until the condition in the for statement is no longer valid. In Python, an iterable refers to anything that can be looped over, such as a string, list, tuple or dictionary. The syntax for looping through an iterable is as follows:

for a in iterable:
print(a)


Example for_loop.py

users = ['Vivek', 'Satya', 'Venu', 'Vasu']

for user in users:
   
    print(user)


 
In the program above, we first declare the list users and give it the members 'Vivek', 'Satya', 'Venu', 'Vasu'. Next the statement for user in users: loops through the users list and assigns each member in the list to the variable user .

The first time the program runs through the for loop, it assigns 'Vivek' to the variable user . The statement print(user) then prints the value 'Vivek'. The second time the programs loops through the for statement, it assigns the value 'Satya' to user and prints the value 'Satya'. The program continues looping through the list until the end of the list is reached.


If you run the program, you’ll get 

 

 Infinite loops

In the case of countdown (refer to program  while_loop.py), we can prove that the loop terminates because we know that the value of n is finite, and we can see that the value of n gets smaller each
time through the loop, so eventually we have to get to 0. Other times a loop is obviously infinite because it has no iteration variable at all. Try to remove the line counter = 5 and run the program.

This will be an infinite loop. Sometimes you don’t know it’s time to end a loop until you get half way through the body. In that case you can write an infinite loop on purpose and then use the break statement to jump out of the loop.

This loop is obviously an infinite loop because the logical expression on the while statement is simply the logical constant True:

Let's see an example  , break.py program

sum = 0
while True:
   
    data = int(input("Enter the data or press 0 to quit :"))
    if data == 0:
        break
    sum = sum+data


print "Sum is ", sum


Here we intend to print the sum of numbers being entered. In the preceding example, the while loop condition has been set to be Boolean, that is, True. In this case, the while loop will continue to execute infinitely as the condition will always be true. However, we can break this loop by setting up a condition check inside the while loop and then using a break statement. So, the loop will continue to run until the user keeps on entering numbers, but it will terminate as soon as the number 0 is entered. Here, once 0 is entered, the if condition inside the while loop will check and as the number entered is 0, the code inside the if block will execute, which is a break statement. This will terminate the loop and print the sum of the numbers entered as shown below:



The break statement

The break statements are used to change the flow of any block of statements. There might be a situation where we might need to break the loop in between; in that scenario, using the break statement will help us achieve our goal.

break_demo.py

attraction_in_Hyderabad = ['Charminar', 'Lumbini Park', 'Golconda Fort',
'Ramoji Film city']
choice = "Golconda Fort"
for place in attraction_in_Hyderabad:
   
    if (place == choice):
       
        break
       
    print (place)


Here we have created a list of attractions available in the city of Hyderabad. We take a variable
choice and assign it a value as "Golconda Fort": We want to print all the places of attraction in Hyderabad. but we would like to stop the moment Golconda Fort occurs in the list. Hence, for every iteration of the for loop, the if block will check each and every element inside the list and compare it with the value we have given to compare, that is, "Golconda Fort". So the program will print all the names appearing before Golconda Fort, and the moment Golconda Fort occurs, the break statement terminates the loop. The output for the program is shown below-

 

There can be several situations where the break statement can be handy such as searching for a keyword in a stack of words, searching a palindrome, and so on. Better to make these programs and master the concept of Loops.

The continue and pass statements

Sometimes you are in an iteration of a loop and want to finish the current iteration and immediately jump to the next iteration. In that case you can use the continue statement to skip to the next iteration without finishing the body of the loop for the current iteration.

Here is an example of a loop that copies its input until the user types “done”, but treats lines that start with the hash character as lines not to be printed (kind of like Python comments).

while True:
    line = input('> ')
    if line[0] == '#':
        continue
    if line == 'done':
        break
    print(line)
print('Done!')





All the lines are printed except the one that starts with the hash sign because when the continue is executed, it ends the current iteration and jumps back to the while statement to start the next iteration, thus skipping the print statement.

The pass statement

There can be scenarios in various programming problems, where you might want to reserve a loop for future use. We may not want to write anything inside the block, but at the same time the block cannot have an empty body. In this case, we use the pass statement to construct a body that does nothing.

pass_demo.py

def doNothing():
       pass
 

for place in "India":
      pass



By doNothing(), we are defining the function with an empty body (functions are yet to be introduced). In this case, the body does nothing (see the screen shot below):




You are allowed to nest loops and other conditional statements in Python, probably infinitely, but it is
best to keep the number of levels of nesting to a minimum. For one thing, it’s very easy to get confused about which option the program is taking at any particular point. Also, having lots of indented blocks within other indented blocks makes your code difficult to read, can slow down the program’s execution, and is generally considered bad style. If you have come up with a design that involves two or three layers of looping, you should probably start thinking about redesigning it to avoid the excessive depth of nesting.
Share:

0 comments:

Post a Comment