Loops

A loop is used for repeated execution of a code block. The code block may contain one or more statements.
Let’s say you want to print table of a number till 10. One way is to write 10 lines.
A more simpler way is to write a single statement and repeat it 10 times using a loop and increment the value of multiplier every time.
[the_ad id=”651″] Loop in Golang
Golang supports only for loop. Unlike many other languages, it does not have a while or a do-while loop. A for loop is written using for keyword.
Syntax of for loop in Golang is

for initialization; condition; increment/decrement {
   // loop statements
}

A for loop statement has following 3 sections each separated with a semi-colon(;).
1. Initialization
A variable, also known as loop counter is initialized here. This variable should be a of numeric type. This section is optional.
2. Condition
Represents the range or limit till when the loop should run. Condition should return a boolean value, either true or false.
Loop runs till the condition remains true. This part is also optional.
3. Increment/Decrement
This is the last section where you either increase the value of loop counter or decrease it. This part is optional as well.
for loop control flow
A for loop execution follows below control flow.

  1. Initialization section is executed where the loop variable is initialized.
  2. Condition is checked. If the condition evaluates to true, then the loop statements are executed.
  3. After the loop body is executed, the loop counter is increased or decreased as per the condition.

[the_ad id=”3528″] for loop examples
Below are all the valid examples of a for loop in Golang. Examples show a loop with all the 3 sections and with one section omitted at a time.

package main

import "fmt"

func main() {
   // loop with all the 3 sections
   for i := 0; i < 5; i++ {
      fmt.Println("Loop counter ", i)
   }

   // loop without initialization section
   i := 0
   for ; i < 5; i++ {
      fmt.Println("Loop counter ", i)
   }   

   // loop without first and third sections
   i := 0
   for ;i < 5; {
      fmt.Println("Loop counter ", i)
   }

   // same as above without semi-colons
   i := 0
   for i < 5 {
      fmt.Println("Loop counter ", i)
   }

   // without condition section
   for i := 0;; i++ {
      fmt.Println("Loop counter ", i)
      if i == 4 {
         break
      }
   }

Following pointers must be kept in mind when omitting for loop sections

  • If you omit the declaration section, then the loop variable should be already declared above.
  • If you omit the increment or decrement section, then the value of loop variable should be increased or decreased inside the loop body else the loop will keep on executing forever.
  • If you omit the condition section,
    • You should write semi-colons to clearly separate initialization and increment sections whether you write them or not.
    • Condition should be checked inside loop body for terminating the loop otherwise it will keep on executing infinitely.

[the_ad id=”656″] Infinite loop
An infinite loop is one which will always keep on executing. Infinite loops are not provided with a condition in the loop declaration.
Terminating condition is checked inside loop body and the loop is terminated using a break statement. There are two ways in which an infinite for loop can be written in Golang.

i := 0
for ;; {
   // perform some task
   i++

   // terminate condition
   if i == 5 {
      break
   }   
}
exit := false
for {
   // perform some task
   
   // terminate condition
   if exit == true {
      break
   }   
}

[the_ad id=”94″] Nested Loops
A loop inside another loop is called a nested loop. When loops are nested, then the outer loop executes first and for each iteration of outer loop, inner loop is executed completely.
This means that the total number of iterations for inner loop are equal to

Total iterations of inner loop = iterations of inner loop  * iterations of outer loop

Nested loops are commonly used to print star or pyramid patterns, sorting and searching of data structures, iterate over multi dimensional data structures and so on.
Example of a nested loop is given below.

package main

import "fmt"

func main() {
   // outer loop
   for i := 1; i < 5; i++ {
      fmt.Println("Outer loop iteration ", i)
      // inner loop
      for j := 1; j < 3; j++ {
         fmt.Println("Inner loop iteration ", j)
      }
      fmt.Println("-----------------------")
   }
}

Note that the loop counter of inner loop should be different than the outer loop. Output of above program is

Outer loop iteration 1
Inner loop iteration 1
Inner loop iteration 2
———————–
Outer loop iteration 2
Inner loop iteration 1
Inner loop iteration 2
———————–
Outer loop iteration 3
Inner loop iteration 1
Inner loop iteration 2
———————–
Outer loop iteration 4
Inner loop iteration 1
Inner loop iteration 2
———————–

Check the total number of times the inner loop is executed.

Loops

Python Loops
Loops are used when same task needs to be executed multiple number of times.
Example, printing mathematical table of a number, printing a message 10 times, sending multiple requests to an end point, creating a menu based application which continues till the user wants etc.
Python provides following loop constructs:

1. while loop
This loop consists of a condition and a set of statements. Set of statements are executed repeatedly till the condition remains True or the condition evaluates to True.
There may be a single condition or multiple conditions separated by and/or operators.  Statements that are inside loop block are called Loop body.
All statements that are part of Loop body are indented, that is, they are at least one space more indented than loop condition and are at the same indentation level.
Syntax

while condition:
   # statement one
   # statement two
   # statement three
   # more statements

Example,

count = 0
# loop till count < 5
while count < 5:        
   # print count value
   print('Count is ' + str(count))  
   # increment count
   count = count + 1
[the_ad id=”651″]

Condition of loop is count < 5 which will remain True till count is less than 5. Loop body consists of 2 statements which are at same indentation level.
Output of the above loop will be

Count is 0
Count is 1
Count is 2
Count is 3
Count is 4

2. for loop

Python for loop can also be used to iterate till a condition remains True but its main use lies in its ability to iterate objects.

These objects may be data structures such as list, tupledictionary or in iterating over a sequence such as a string where it provides access to each item in the data structure and keeps on iterating till all the items are covered.
for loop syntax
Looking at both the above usages of for loop, its syntax can be generalized as below:

for <variable name> in <data structure or limit>:
     # statement one
     # statement two
     # other statements

Notice the in keyword and a colon(:) at the end. Also, all the statements of for loop are indented to denote that they belong to same block.
Using for loop
A for loop can be used in the following two scenarios.

Iterate using an index
Many times you want to iterate for a definite number of times using a counter or an index variable. Example, from 1 to 10. Using for loop this can be done as

for index in range(5):
   # prints 0 to 4
   print(index)

where index is a user defined variable and range() is an in-built method which returns a range of numbers starting from 0 to 1 less than the argument passed to it.
Thus, range(5) returns numbers from 0 to 4.

Iterate over a data structure
Suppose there is a list of items and you want to iterate it over that list using a for loop. Code will be

# create a list
fruits = ['papaya', 'orange', 'mango', 'banana'] 
for fruit in fruits:
    print(fruit)

Output of above code will be

papaya
orange
mango
banana

[the_ad id=”89″] Loop with String
for loop can be used to iterate over a python string where element in each iteration will be a character. Example,
str = 'cat'
for char in str:
   print(char)

which prints

c
a
t

range() function
Python range() function generates a sequence of integers according to the arguments given to it.
range() function accepts following three arguments:
A. start
An integer which signifies the beginning value of the sequence to be generated. This is optional with a default value of 0.

B. end

An integer which signifies the end value of the sequence to be generated. This parameter is required.
Last value of the sequence generated by range() will be (end – 1).

C. step
An integer that defines the difference between the values generated. Thus, step size of 3 means two adjacent values will have a difference of 3.
step is optional with default value of 1.

for loop can be used to iterate over values generated by range() function using in operator. Thus, following is an example program to iterate 10 times using a for loop and range().

for num in range(10):
    print(num)

Else with for loop
Sometimes you want some code to be executed just after the loop ends or when there are no items left to be iterated.
For such cases, a for loop may be followed by an else block written using else statement. This block is optional. Example,

for x in 'cat':
   print(x)
else:
   print('End of characters')

which prints

c
a
t
End of characters

[the_ad id=”647″] pass statement
If a for loop is written, it can not be empty, that is it should have at least one statement else there will be an error.
But if you want an empty for loop, may be for testing purpose, then write a pass statement inside the empty loop as shown below.
for x in range(3):
   pass

This loop will do nothing.
If you write pass in a loop that has other statements as well, then pass is completely ignored and the loop executes normally.
break statement
Python break statement is used to terminate a loop in between based on some condition.
Suppose you are searching for a name in a list of students using a loop. Now, it makes no sense to iterate further once the desired name is found. Example,

names = ['A', 'B', 'C' , 'D']
for name in names:
    if name == 'C':
        break
    print(name)

This prints

A
B

From the output, it is clear that the loop terminates in between.
Nested Loop
A loop inside another loop is called nested loop. A nested loop, also called inner loop is executed for each iteration of the outer loop just like any other statement written in outer loop.
Nested loop are mostly used for sorting structures where you need to compare each element with every other element or where there are two dimensional structures such as a matrix of numbers.
Example of a nested loop is

for x in range(3):
   for y in range(2):
      print('Outer variable = %d, Inner variable = %d' %(x,y))

which prints

Outer variable = 0, Inner variable = 0
Outer variable = 0, Inner variable = 1
Outer variable = 1, Inner variable = 0
Outer variable = 1, Inner variable = 1
Outer variable = 2, Inner variable = 0
Outer variable = 2, Inner variable = 1

Note that inner loop is completely executed for each iteration of outer loop, and

Total inner loop iterations = Outer loop iterations * Inner loop iterations per outer loop iteration

[AdSense-A] Hope the article was useful.
Exit mobile version