Loops In Python

There are two types of loops in python.

  • While Loop
  • For Loop

While Loop

With While loop we can execute a code as long as a condition is true. Example:

i = 1
 while i < 6:
   print(i)
   i += 1

This code will print value of i as long as the value of i is less than 6

With the break keyword we can stop a loop when a specify condition become true Like

The break

i = 1
 while i < 6:
   print(i)
     if i == 3:
    break
  i += 1 

In this code when value of i become 3 the loop will stop and move to next code.

The continue

With continue keyword we can skip a loop one step if a given condition become true like.

i = 0
 while i < 6:
     i += 1 
  if i == 3:
    continue
  print(i)

In this code number 3 will be skipped and all other values are printed

else in while loop

In python there is a else keyword which will execute after while loop finish its working. The main thing is that if loop is finished using break statement else block will not execute. else block only execute when while loop is successfully completed.

For Loop

For loop is used to run statements for each item of python collection. It will execute a block of code until the items in a collection will finished. For example

fruits = ["apple", "banana", "cherry"]
for    x in fruits:
   print(x)

This code will print all fruit names available in list

String Loop

For loop can also be used for string to loop each character of string.

for x in "banana":
  print(x)

Break & Continue

Break and continue are the same as described previously

Nested

For loops can also be used in nested. Like for loop inside the for loop like.

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
   
for x in adj:
  for y in fruits:
    print(x, y) 

This code will execute for each item of adj and also execute for each item of fruits but with adj variable’s one item fruits loop complete and same for other items.

pass statement

Pass statement is using for do nothing If you want to leave empty inner block of loop use the pass statement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s