PY0011 Python For & While Loops: Enumerate, Break, Continue Statement
Posted by Superadmin on November 10 2018 13:39:19

What is Loop?

Loops can execute a block of code number of times until a certain condition is met. Their usage is fairly common in programming. Unlike other programming language that have For Loop, while loop, dowhile, etc.

What is For Loop?

For loop is used to iterate over elements of a sequence. It is often used when you have a piece of code which you want to repeat "n" number of time.

 

What is While Loop?

While Loop is used to repeat a block of code. Instead of running the code block once, It executes the code block multiple times until a certain condition is met.

In this tutorial, we will learn

How to use "While Loop"

While loop does the exactly same thing what "if statement" does, but instead of running the code block once, they jump back to the point where it began the code and repeats the whole process again.

Syntax

while expression
 Statement  

Example:

#
#Example file for working with loops
#
def main():
	x=0
	#define a while loop
	while(x <4):
		print(x)
		x = x+1

if __name__ == "__main__":
    main()

How to use "For Loop"

In Python, "for loops" are called iterators.

Just like while loop, "For Loop" is also used to repeat the program.

But unlike while loop which depends on condition true or false. "For Loop" depends on the elements it has to iterate.

Example:

#
#Example file for working with loops
#
def main():
	x=0
	#define a while loop
#	while(x <4):
#		print x
#		x = x+1


	#Define a for loop 
for x in range(2,7):
		print(x)


if __name__ == "__main__":
    main()

For Loop iterates with number declared in the range.

For example,

For Loop for x in range (2,7)

When this code is executed, it will print the number between 2 and 7 (2,3,4,5,6). In this code, number 7 is not considered inside the range.

For Loops can also be used for a set of other things and not just number. We will see thin in next section.

How to use For Loop for String

In this step, we will see how "for loops" can also be used for other things besides numbers.

Example:

def main():
	#use a for loop over a collection
	Months = ["Jan","Feb","Mar","April","May","June"]
	for m in Months:
		print(m)
		
if __name__ == "__main__":
	main()

Code Line 3: We store the months ("Jan, Feb , Mar,April,May,June") in variable Months

Code Line 4: We iterate the for loop over each value in Months. The current value of Months in stored in variable m

Code Line 5: Print the month

How to use break statements in For Loop

Breakpoint is a unique function in For Loop that allows you to break or terminate the execution of the for loop

Example:

	
def main():
	#use a for loop over a collection
	#Months = ["Jan","Feb","Mar","April","May","June"]
	#for m in Months:
		#print m
		
# use the break and continue statements
		
		
		for x in range (10,20):
			if (x == 15): break
			#if (x % 2 == 0) : continue
			print(x)

if __name__ == "__main__":
	main()
In this example, we declared the numbers from 10-20, but we want that our for loop to terminate at number 15 and stop executing further. For that, we declare break function by defining (x==15): break, so as soon as the code calls the number 15 it terminates the program Code Line 10 declare variable x between range (10, 20)

How to use "continue statement" in For Loop

Continue function, as the name indicates, will terminate the current iteration of the for loop BUT will continue execution of the remaining iterations.

Example

def main():
	#use a for loop over a collection
	#Months = ["Jan","Feb","Mar","April","May","June"]
	#for m in Months:
		#print m
		
# use the break and continue statements
		
		
		for x in range (10,20):
			#if (x == 15): break
			if (x % 5 == 0) : continue
			print(x)

if __name__ == "__main__":
	main()

Continue statement can be used in for loop when you want to fetch a specific value from the list.

In our example, we have declared value 10-20, but between these numbers we only want those number that are NOT divisible by 5 or in other words which don't give zero when divided by 5.

So, in our range (10,11, 12….19,20) only 3 numbers falls (10,15,20) that are divisible by 5 and rest are not.

So except number 10,15 & 20 the "for loop" will not continue and print out those number as output.

How to use "enumerate" function for "For Loop"

Enumerate function in "for loop" does two things

Example:

Enumerate function is used for the numbering or indexing the members in the list.

Suppose, we want to do numbering for our month ( Jan, Feb, Marc, ….June), so we declare the variable i that enumerate the numbers while m will print the number of month in list.

def main():
	#use a for loop over a collection
	Months = ["Jan","Feb","Mar","April","May","June"]
	for i, m in enumerate (Months):
		print(i,m)
		
# use the break and continue statements
		
		
		#for x in range (10,20):
		#if (x == 15): break
		#if (x % 5 == 0) : continue
		#print x


		
if __name__ == "__main__":
	main()

When code is executed the output of the enumerate function returns the months name with an index number like (0-Jan), (1- Feb), (2- March), etc.

Pratical Example

Let see another example for For Loop to repeat the same statement over and again.

Python loop

Working Code for all exercises

Code for while loop

def main():
   x=0    
   while (x<4):
      
       print x
       x= x+1
if __name__== "__main__":
  main()  

For Loop Simple Example

def main():
   x=0 
      
   for x in range (2,7):
      
       print x
    
if __name__== "__main__":
  main()        
    
   

Use of for loop in string

def main():
       
    Months = ["Jan","Feb","Mar","April","May","June"]
    for m in (Months):
        print m
        
if __name__== "__main__":
 main()

Use break-statement in for loop

def main():
       
   for x in range (10,20):
       if (x == 15): break
       print x
    
if __name__== "__main__":
  main()  

Use of Continue statement in for loop

def main():
       
   for x in range (10,20):
       if (x % 5 == 0): continue
       print x
    
if __name__== "__main__":
  main()        

  

Code for "enumerate function" with "for loop"

def main():
     
    Months = ["Jan","Feb","Mar","April","May","June"]
    for i, m in enumerate (Months):
        print i,m
        
if __name__== "__main__":
  main()     
      

How to use for loop to repeat the same statement over and again

You can use for loop for even repeating the same statement over and again. Here in the example we have printed out word "guru99" three times.

Example: To repeat same statement number of times, we have declared the number in variable i (i in 123). So when you run the code as shown below, it prints the statement (guru99) that many times the number declared for our the variable in ( i in 123).

for i in '123':
 print "guru99",i,

Like other programming languages, Python also uses a loop but instead of using a range of different loops it is restricted to only two loops "While loop" and "for loop".

Python 2 Example

Above codes are Python 3 examples, If you want to run in Python 2 please consider following code.

# How to use "While Loop"
#Example file for working with loops
#
def main():
	x=0
	#define a while loop
	while(x <4):
		print x
		x = x+1

if __name__ == "__main__":
    main()

#How to use "For Loop"
#Example file for working with loops
#
def main():
	x=0
	#define a while loop
#	while(x <4):
#		print x
#		x = x+1


#Define a for loop 
for x in range(2,7):
		print x


if __name__ == "__main__":
    main()

#How to use For Loop for String
def main():
	#use a for loop over a collection
	Months = ["Jan","Feb","Mar","April","May","June"]
	for m in Months:
		print m
		
if __name__ == "__main__":
	main()

#How to use break statements in For Loop
def main():
	#use a for loop over a collection
	#Months = ["Jan","Feb","Mar","April","May","June"]
	#for m in Months:
		#print m
		
# use the break and continue statements
		for x in range (10,20):
			if (x == 15): break
			#if (x % 2 == 0) : continue
			print x

if __name__ == "__main__":
	main()

#How to use "continue statement" in For Loop
def main():
	#use a for loop over a collection
	#Months = ["Jan","Feb","Mar","April","May","June"]
	#for m in Months:
		#print m
		
# use the break and continue statements		
		for x in range (10,20):
			#if (x == 15): break
			if (x % 5 == 0) : continue
			print x

if __name__ == "__main__":
	main()

#How to use "enumerate" function for "For Loop"
def main():
	#use a for loop over a collection
	Months = ["Jan","Feb","Mar","April","May","June"]
	for i, m in enumerate (Months):
		print i,m
		
# use the break and continue statements
		#for x in range (10,20):
		#if (x == 15): break
		#if (x % 5 == 0) : continue
		#print x
	
if __name__ == "__main__":
	main()