Loops in Python- I

When there is a need to execute the same block of code over and over again, the process is called iteration and this iteration is implemented by a programming structure called Loop. Loops are used to alter the flow of any program, whose execution flow is sequential by default. In many cases, it is desirable to repeat any code a number of times. For this, Python provides different types of loops which are capable of repeating any code several numbers of times as desired.

Advantages of loops

  • Code reusability.
  • No need to write the same code again and again.
  • Can traverse over the elements of data structures.

 Types of loops

Broadly classified, there are two types of iteration, indefinite and definite:

  • With indefinite iteration, the number of times the loop is executed isn’t specified in advance. The designated block is executed repeatedly as long as the given condition is met. The while loop is used when we don’t know the number of iterations in advance. The block of statements is executed until the condition specified in the while loop is satisfied. It is also called a pre-tested loop.
  • In definite iteration, the number of times the loop is executed isn’t specified in advance. The for loop is used when we need to execute some part of the code until the given condition is satisfied. The for loop is also called a pre-tested loop. It is better to use for loop if the number of iterations is known in advance.

The while loop

The while loop syntax is:

<statement(s)> refers to the body or block to be repeatedly executed. Like we read in the if- else conditional statement, the indentation rule will be followed here as well.

The control expression, <expr>, involves one (or more) variable that is initialized prior to starting the loop and then modified somewhere in the loop body. This <expr> evaluates as either True or False. The loop executes again and again for as long as the <expr> is true. When the <expr> becomes false, the execution of the first statement beyond the body loop takes place. Let’s code it down and understand the concept first.

# WAP to print all positive numbers below a given number?

I have a number, say 5. I want to print all positive numbers below 5, i.e., 4, 3, 2, 1, 0. What should I do? In English, I could say that while my number 5 is greater than zero, I’ll decrement my number and print every time. When 5 becomes 4, print 4, 4 becomes 3, print 3 and so on. For this, the print statement should be inside the loop. Let’s code it now.

I think the code is clear. As long as number n is greater than 0, n = n-1 will execute. First n = 5. While 5 > 0, n = 5-1 = 4, and 4 will be printed. Now n = 4. It’s still greater than zero. So, n = 4-1 = 3, and 3 will be printed. Now n = 3. It’s still greater than zero. So, n = 3-1 = 2 and 2 will be printed. Now n = 2-1 = 1 and 1 will be printed. Now n = 1. It’s still greater than zero. So, n = 1-1 = 0, and 0 will be printed. When n becomes zero, now it’s not greater than zero, as per theory, True condition has been executed and it comes out of the loop. What will happen if this print statement will be printed outside the loop?

Ok. It’ll only display the final output. All values are executed but the print is outside the loop, so no values are printed. We read that, when True condition is executed, the first statement after the loop is executed. The first statement here is print. 

What if I want to print up to a certain value or I want to skip some value and print the remaining values? For this, two keywords are used: break and continue. The break statement immediately terminates a loop completely. The continue statement immediately terminates the current loop iteration and jumps to the top of the loop. The control expression is evaluated again to determine whether the loop will execute or terminate.

We have taken a number 5. As explained before, 5>0, the next line will be 5-1 = 4. Then, it will check if 4 is equal to 2. It’s not equal. So it will not go inside the if statement condition. 4 will be printed. Now num = 4. 4>0, so the next line will be 4-1 = 3. Then, it will check if 3 is equal to 2. It’s not equal. So it will not go inside the if statement condition. 3 will be printed. Now the number is 3. 3>0, the next line will be 3-1 = 2. Then, it will check if 2 is equal to 2. It’s equal. So it will go inside the if statement condition. Inside if condition there is a break statement. It will immediately terminate the entire execution and will come out of loop and outside loop there is a print message. So, the message will be printed. Let’s check how the continue works?

The loop will be executed as explained above, till the number is equal to 2. When num becomes 2, the continue statement executes the iteration. 2 will not be printed, and execution returns to the top of the loop. The condition is evaluated again, and it is still true. The loop resumes, terminating when number becomes 0, and will come out of the while loop, printing the final message.

The while- else loop

While- else loop is a unique feature of python. Else clause is optional. The syntax is:

When the while loop executes, then, else clause is executed. One important thing to remember is that if the loop is terminated by a break statement, the else clause will not be executed. Let’s see how it works.

After the entire while loop is executed, then, the else loop will also get executed. What if I write this final print statement without the else clause?

Both answers are the same. The only difference is that the else clause thinks that a False condition has occurred. So, it executes. While without else, the execution is because the true condition has been completed and it comes out of the loop. Whatever is out of the loop that condition will get executed. It is not considered as True or False. It’s just a condition to be executed. That’s why this else clause is optional.

As stated, with a break statement, the else clause does not work. In this case, you can assume that it’s working like while num > 0 behaves as if (while (num > 0)), executing over and over again till break condition is encountered. Since, here while acts as if, the else will not be executed like in if- else case, where, either if or else executes.

Design a site like this with WordPress.com
Get started