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. 

0 Comments:

Post a Comment

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (114) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (89) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (741) Python Coding Challenge (192) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses