Sunday, 17 February 2019

Loops in Python

Loops are used in cases where you need to repeat a set of instruction over and over again until a certain condition is met. There are two primary  types of looping in Python.
  • For Loop
  • While Loop

For Loop

Python Code:
for i in range(1,10):
  print(i, end=' ')

A for loop contains three operations. The first operation i is initializing the loop iterator with first value of range function. range function is supping values as iterator from (1,10).for loop catches the Stop Iterator error and breaks the looping.

Output:
1 2 3 4 5 6 7 8 9

While  Loop

Python Code:
i = 0
while i < 10:
  print(i, end= ' ')
   i+=1

Output:
1 2 3 4 5 6 7 8 9

A while loop variable is initialized before the statement. Here we initialized i to 0. In the while statement, we have kept until when the loop is valid.

So here we check up to i < 10. Inside the while loop we are printing i and then incrementing it by 1.
Imagine what would happen if we don't increment i by 1?
The loop will keep running a concept called infinite loop. Eventually the program will crash.

Break and Continue:

Break Statement:

A break statement will stop the current loop and it will continue to the next statement of the program after the loop.

Python Code:
i = 0
while i < 10:
   i+ = 1
   print(i, end=' ')
    if i == 5:
       break

Output:
1 2 3 4 5

In the above random example, we are incrementing i from an initial value of 0 by 1. When the value of i is 5, we are breaking the loop.

Continue Statement:

Continue will stop the current iteration of the loop and it will start the next iteration.It is very useful when we have some exception cases, but do not wish to stop the loop for such scenarios.

Python Code:
i = 0
while i < 10:
  i+ = 1
  if i%2 == 0:
     continue
  print(i, end= ' ')

Output:
1 3 5 7 9

In the above example, we are skipping all even numbers via the id conditional check i%2.So we end up printing only odd numbers. 

1 comment:

Popular Posts

Categories

Android (21) AngularJS (1) Books (3) C (75) C++ (81) Data Strucures (4) Engineering (13) FPL (17) HTML&CSS (38) IS (25) Java (85) PHP (20) Python (83) R (68) Selenium Webdriver (2) Software (13) SQL (27)