Applied Programming/Loops


This lesson introduces loops, including while, for, do and other loops. Loops allow you to repeat similar operations in your code. A loop executes a block of code until the loop has iterated over an object. In a for loop, as will be further explained, the loop runs until it has iterated over every item in an iterable. For loops help you reduce repetition in your code because they let you execute the same operation multiple times. All loops are sequences of instructions designed to be repeated until a certain condition is met or achieved. Loops only need to be written once but may repeat multiple times over. Because of this, they are used to do certain tasks multiple times based on the program's task, avoiding having to create extra, unnecessary steps in a program. [1]

What are loops:Edit

Loops are a fundamental construct for many programs. In fact, all but the most basic of programs are likely to include at least one loop in them. Loops can be very useful and can save you, the developer, a lot of time. [2]

We can elaborate on the time-saving part. Let's consider a situation when you want to print Hello, World! five times.

print("Hello, World!")
print("Hello, World!")
print("Hello, World!")
print("Hello, World!")
print("Hello, World!")


Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

It was simple, but again, let's consider another situation when you want to write Hello, World! a thousand times. We can certainly not write print() statements a thousand times. Almost all the programming languages provide a concept called loop, which helps in executing one or more statements up to a desired number of times. All high-level programming languages provide various forms of loops, which can be used to execute one or more statements repeatedly. [3]

Loop Structure:Edit

They allow you to run one or more lines of code repetitively. You can repeat the statements in a loop structure until a condition is True, until a condition is False, a specified number of times, or once for each element in a collection.[4]

The following fall under the Loop Structure:

-While Loop

-Do-While Loop

-For Loop

-Break Statement

-Continue Statement[5]

Types of loops:Edit

For loop:Edit

It enables a particular set of conditions to be executed repeatedly until a condition is satisfied.[6] Below is a following example of a For Loop:

 for x in range(0, 3):
   print("We're on time %d" % (x))

The Python for statement iterates over the members of a sequence in order, executing the block each time. They are traditionally used when you have a block of code which you want to repeat a fixed number of times.[7]

While loop:Edit

While loops are implemented when there is specific condition to satisfy or to follow. The while loop can be terminated whenever the conditional statement is not satisfied. In other words, when the while loop's test expression becomes false, the code inside of the while loop is neglected, and the following code is executed immediately. [8]

#While loop Format
  While Expression

Another way to implement the while loop is control the number of repetitions. The repetition of the while can be determined with control variable.

#While loop repetition Format
 n = 0  #repetition control variable
 While (n < 5): n = n + 1; # the repetition of the loop is limited to 5 times, incrementing by 1 each time.
#While loop repetition example
 n = 0
 while (n < 5): n = n + 1; print(“Welcome to CIS206”)

The output gives below results:

Welcome to CIS206
Welcome to CIS206
Welcome to CIS206
Welcome to CIS206
Welcome to CIS206

In the while loop operation, there are two distinguished control expressions: "break" and "continue." [9] The use of either break or continue allow more than one conditional statements inside the while loop. break terminates while loop immediately. continue shifts to the alternative conditional statement as long as original while loop's conditional statement is True.

#While loop - Break example
 n = 3
 while n > 0:
   n = n + 1
   if n == 1:
     break  #break is engaged if the while loop is repeated once
   print (n)
 print('Loop is terminated')
#While loop - Continue example
 n = 3
 while n > 0:
  n = n + 1
  if n == 2:
    continue #continue is engaged if the while is repeated twice
   print (n)
  print('Loop is terminated')

Do-while loop:Edit

Do-while has distinctive difference from the regular while loop. The difference is that the Do-while is executed at least once. [10] Do-while loop is initiated with conditional statement(s).

#Do-while loop template
 n = 0 #number of repetition controller
 while True:
   n = n + 1 
   if (n > 5);
      break #when the execution is repeated five times, the while operation is terminated

Infinite loop:Edit

An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. Typically, a certain process is done, such as getting an item of data and changing it, and then some condition is checked, such as whether a counter has reached a prescribed number. If the presence of the specified condition cannot be ascertained, the next instruction in the sequence tells the program to return to the first instruction and repeat the sequence, which typically goes on until the program terminates automatically after a certain duration of time, or the operating system terminates the program with an error.[11]

In most cases, infinite loops are unintentional and the result of poor programming. However, there are situations in which infinite loops can be used intentionally. The most common occurrence of this is with the modern computer. Modern interactive computers require that the computer constantly be monitoring for user input or device activity, so at some fundamental level there is an infinite processing idle loop that must continue until the device is turned off or reset.[12]


   apples = 4
   while apples > 3:
       print("You have " + apples + " apples.")
       apples = apples + 1
   You have 4 apples.
   You have 5 apples.
   You have 6 apples.
   You have 7 apples.
   You have 8 apples.

In the example above, the loop is intended to break when the number of apples is at or below three. However, the variable "apples" starts at four. With each iteration of the loop, "apples" increases by one. In this case, "apples" will never fall to zero, and the loop repeats infinitely.

   while True:
       print("This statement is true")
       print("This statement is not true")
   This statement is true
   This statement is true
   This statement is true
   This statement is true

In this example, the programmer has failed to create a break statement to exit the loop. Because there is no break statement or any code that would cause the loop to be "false", the loop repeats infinitely.

Nested loop:Edit

A nested loop occurs when one loop is placed inside the body of another loop. The inside loop is executed each time the outer loop is executed.


   i = 1
   j = 5
   while i < 4:
       while j < 8:
           print(i, ",", j)
           j = j + 1
           i = i + 1
   1 , 5
   2 , 6
   3 , 7


The function above contains two "while" loops; one nested within the other. The outer loop is executed first with "i" being less than four. This causes the internal loop to execute with "j" being less than 8. The function then breaks when "i" is no longer less than 4; on the fourth iteration.

Loop keywords:Edit

Break Statement - This statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the statement is inside a nested loop (loop inside another loop), the statement will terminate the innermost loop.

Condition - This statement a loop checks in order to decide if it should loop again or stop looping.. It's a set of rules performed if a certain condition is met. It is sometimes referred to as an If-Then statement, because IF a condition is met, THEN an action is performed.

Continue Statement - This statement is used inside loops. When the statement is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of statements inside the body of loop for the current iteration.

Counting controlled - A loop where a variable (such as a counter) determines how many times a loop will run.

Do-While Loop - A do-while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block.

Exit - A predefined function used to prematurely stop a program and return to the operating system . It is used to finish or exit the execution of an enclosing loop statement. If the statement includes a condition, then the exit from the loop is conditional. .

Flag - Commonly used to control or to indicate the intermediate state or outcome of a particular operation. It is the value that acts as a signal for a function or process. The value is used to determine the next step of a program

For Loop - A for loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly. A for loop has two parts: a header specifying the iteration, and a body which is executed once per iteration.

For each Loop - For each (or foreach, sometimes called an iterative for-loop) is a control flow statement for traversing items in a collection.

Goto - An unstructured branching command that makes the logic in a program jump to a different location

Infinite Loop (or Endless Loop) - A sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition or having one that can never be met.

Iteration Control Structure - A statement or block that is executed until the program reaches a certain state, or operations have been applied to every element of a collection or array.

Loop Counters - Variable that controls the iterations of a loop (a computer programming language construct). It is named because most uses of this construct result in the variable taking on a range of integer values in some orderly sequences.

Nested Loop - A loop within a loop. The inner loop will repeat depending on the number of iterations in the outer loop.

Pass Statement - This statement is used as a placeholder for future code. When the statement is executed, nothing happens; but you avoid getting an error when empty code is not allowed.

Raise - This keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user.

Return - A branching statement that causes a function to jump back to the function that called it. Allowing it to be also used as a way to break out of a loop. A return statement returns occasional results from a function or simply finishes a function. There is an implicit return at the end of any function, so you do not need to use one if your function ends naturally, without returning any value.

Sentinel value - It's a special value in the context of an algorithm which uses its presence as a condition of termination, typically in a loop or recursive algorithm. The value is a form of in-band data that makes it possible to detect the end of the data when no out-of-band data (such as an explicit size indication) is provided.

While Loop - A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.


  12. Infinite Loop
  13. BeginnersBook