Loops in Python

loops in python

The ability to make decisions is a critical component of most computer programs.  Another is the ability to repeat or loop the program through a specific set of tasks.  All programs, other than those that perform a specific task and exit, contain at least one loop.  Typically, this is the main loop, where the program continually loops waiting for user or object input for it to act upon.  Additionally, loops can be used to apply repetitive processes on objects using a compact set of instructions.

Python has two primary loop commands: 

  • While loops
  •  For loops

 They both allow for the repetitive looping through a specific operation, but differ in how they test if the loop should continue to be processed.

While Loop in python

The While loop is used to execute a set of statements as long as the condition remains true.

 Example: 

Print "Hello" as long as i is less than 5:

 i = 1 

while i < 5: 

print("Hello")

 i += 1

Always remember to increment i inside the loop or else the loop will continue forever. 

The break Statement in python

 The break statement is used to stop the loop at that exact instance even if the while condition is true.

 Example:

 Exits the loop when i is 3: 
i = 1 
while i < 6:
   print(i) 
if i == 3: 
Break
 i += 1 

The continue Statement 

The continue statement is used to stop the current iteration, and continue with the next. 

Example: 

Continue to the next iteration if i is 3:
 i = 0 
while i < 5:
i += 1 
if i == 3: 
continue 
print(i) 

The else Statement in python

The else statement is used to run a block of code once when the condition is no longer true. 

Example: 

Print a message once the condition is false:
 i = 1 
while i < 6: 
print(i)
 i += 1 
else: print("i is no longer less than 6")

 For Loop in python

 A for loop is used to iterate over a sequence (can be a list, a tuple, a dictionary, a set, or a string).

 This is different from the for keyword in other programming languages and works more like an iterator method as found in other object-orientated programming languages.

Using the for loop, we can execute a set of statements, once for each item in a list, tuple, set etc.

 Example: 

Print each color in a colors list:
colors = ["red", "yellow", "green"]
for color in colors: 
  print(color) 

The break Statement in python

We can also use the break statement with the for loops to stop the loop before it has looped through all the items.

 Example:

Exit the loop when color is "blue": 
colors = ["red", "blue", "yellow"] 
for color in colors:
 print(color) 
if color == "blue": 

     break 

Output: red

         blue                         //blue is printed because the if statement is used after that 

The range() Function  in python

The range function can also be used with loops in Python. When you loop through a set of code a specified number of times, you can use the range() function. 

The range() function returns a sequence of numbers. It starts from 0 by default, and gets incremented by 1, and ends at a specified number. 

Example:

Using the range() function: 
for x in range(6): 
   print(x) 

The range() function starts with 0 by default, however it is possible to specify the starting value yourself. You can do this by adding a parameter: range(2, 6), which means values from 2 to 6 (does not include 6). 

Example: 

Using the start parameter: 
for number in range(2, 6): 
print(number)                                //You can use any variable instead of number

Nested Loops in python

A nested loop is a loop inside of another loop. The “inner loop” will be executed one time for each iteration of the “outer loop”.

 Example:

 Print each quantity for every product:
 quantity = ["10", "25", "20"]
 products = ["mobiles", "chargers", "books"] 

for x in quantity:
 for y in products: 
    print(x, y) 


Output: 
10 mobiles 
25 chargers 
20 books 

 Looping Through a String

Even strings are iterate objects as they contain a sequence of characters. Here I will show you how to loop through letters in a string.

 Example:

Loop through the letters in the word "United Kingdom": 
for x in "United Kingdom": 
print(x) 

Output:
United Kingdom