Python Loop Control Statements – Python Programming

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

Python Loop Control Statements - Break Statement, Continue Statement,Pass Statement, Python Iterator and Generator

There are three types of Loop Control Statements:

  1. Break Statement
  2. Continue Statement
  3. Pass Statement
Python Loop Control Statements Video Tutorial

Break Statement in Python

With the break statement we are able to stop the loop before it goes 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 are able to 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 employed once an announcement is needed syntactically however you are doing not wish any command or code to execute.

The pass statement could be a null operation; nothing happens once 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

Python Iterator is an in-built function which allows traversing through all the elements of a collection.

A generator is a function that produces or yields a sequence of values using the 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))

Whats Next – Python Date Time

Share