Python – Loop Control Statements

The Loop control statements change the execution from its normal sequence. It can be used with While Loop and For Loop

Types of Loop Control Statements

There are three types of statements:

  1. Break Statement
  2. Continue Statement
  3. Pass Statement

Break Statements in Python

With the break statement we can stop the loop before it has looped through all the items:

While Loop Break Statement

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

For Loop Break Statement

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

Continue Statement in Python

With the continue statement we can stop the current iteration of the loop, and continue with the next:

While Loop Continue Statement

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

For Loop Continue Statement

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

Pass Statement in Python

The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

The pass statement is a null operation; nothing happens when it executes. The pass statement is also useful in places where your code will eventually go, but has not been written yet

for letter in 'StudyGyaan': 
   if letter == 'G':
      pass
      print ('This is pass block')
   print ('Current Letter :', letter)

Python Iterator

Iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation.

A generator is a function that produces or yields a sequence of values using yield method.

list1 = [1,2,3,4]
iter1 = iter(list1) # this builds an iterator object
print ("\n",next(iter1)) #prints next available element in iterator
print (next(iter1))
print (next(iter1))
print (next(iter1))
Filed under: Python

No comment yet, add your voice below!


Leave a Reply