Python Loops


Python Loops:

Basically,python have two type of loops.

  • while loop
  • for loop

1.while loop:

The while statement will get executed as long as the conditions inside it is true.

Example:

i = 0
while i < 9:
  print(i)
  i = i+1 

#(i = i + 1)it can written as (i += 1).Here (i) is incremented by 1.

Output:
0
1
2
3
4
5
6
7
8


Using break keyword in while loop:

>> using break keyword we can stop the execution of while loop even after the condition is true.

Example:

i = 0
while i < 9:
  print(i)
  if i == 4:             
      break  
  i = i+1

Output:
0
1
2
3
4

In above example when i = 4 the loop break and execution stop.


Using continue keyword in while loop:

>> using continue keyword we can stop the current execution or we can skip the current step.

Example 1:

i = 0
while i < 9:
  print(i)
  if i == 4:              
       continue  
  i = i+1

Output:
0
1
2
3
5
6
7
8

In the above example at i = 4 the 4 value has been skipped and it is not printed.



2.for loop:

A for loop is used for iterating over a sequence,using for loop we can execute a set of statement according to the given conditions.


Syntax:

for i in range(start,end,step):
   print(i)

Example 2:

for i in range(0,5,1):
   print(i)

Output:
0
1
2
3


Note that range(0,5) is not the values of 0 to 5, but the values 0 to 4. 

Note: for i in range(0,5,1) can be written as:
  1. for i in range(5) # 0 and 1 are taken by default.

Example 2.1:

for x in range(26):
  print(x)


Output:
2
3
4
5

Example 2.3:

for x in range(2,9,2):
  print(x)


Output:
2
4
6
8


Using for loop in list:

Example:

cars = ["BMW""MERCEDES""TOYOTA"]
for x in cars:
  print(x)

Output:
BMW
MERCEDES
TOYOTA


Using for loop in a string:

Example:

fruit = "banana"
for x in fruit:
  print(x)

Output:
b
a
n
a
n
a



3.Nested loop:

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

Example:

color = ["red""blue""pink"]
cars = ["BMW""Mercedes""Toyota"]
for x in color:
  for y in cars:
    print(x, y)


Output:

red BMW
red Mercedes
red Toyota
blue BMW
blue Mercedes
blue Toyota
pink BMW
pink Mercedes
pink Toyota

In the above the example the when outer loop execute one time the inner loop execute 3 times.



Post a Comment

0 Comments