sampleqa.in tutorials, Python Programming  tutorial

Python Loop Statements


    Python supports following loop statements, loops are mainly used on numeric calculations and to loop through collection of items, like arrays,sequence objects or iterables

  • for loop
  • while loop

Python For Loop

syntax:
 		for  element in  sequence:
 		     statement 1
 		     statement 2
 		     ...
 		     statement N
 		[else:
 		    statement 1...statement N]	
 	

Python While Loop

     While loop, repeates the execution of suite of statements specified by the number of times. if condition is non-zero loop body will execute, otherwise executes optional else block of code.if specified.

syntax:
 		while condition :
 		     statement 1
 		     statement 2
 		     ...
 		     statement N
 		[else:
 		    statement 1...statement N  ]
 	

For loop and Range object

    Range object is a another Object in Python, Whcih returns sequence of integers,
Range Object has 2 forms

  • range(stop_exclusive)
  • range(start_inclusive,stop_exclusive,step)
 	  i.e  range(10)   means   0..9 excludes  10
 	  similaryly range(1,10)   means 1..9 10 exclusive
 	   range(2,10,2) means 10 is exclusive, so upto 8 will be considered.
 	   
Example: Print numbers from 1..5 using for loop range object
 	   	>>>for i in range(1,6):
 	   	     print(i, sep = ' ', end = ' ')
 	   	     
 	   	    -- starting from 1(inclusive) end is 6 exclusive, so 1..5 
 	   
Output
 	   	1 2 3 4 5
 	   
Example: Print even numbers using for loop and range object
 	   	>>>for i in range(2,10,2):
 	   	     print(i, sep = ' ', end = ' ')
 	   	     
 	   	    -- starting value is 2(inclusive) ending value  is 10 exclusive, step by 2,  
 	   
Output
 	   	2 4 6 8
 	   
Example: Print Numbers in decreasing Order using loop and range object
 	   	>>>for i in range(5,0,-1):
 	   	     print(i, sep = ' ', end = ' ')
 	   	     
 	   	    -- starting value is 5(inclusive) ending value  is 0 exclusive, step by -1, 
 	   	    	first iteration ->starting value is 5
 	   	    	second iteration -> starting value - step  i.e  5-1=4
 	   	    	......
 	   	    	
 	   	     
 	   
Output
 	   	5 4 3 2 1
 	   

For loop and String object

     In Python String is a iterables Object,so it can be used in for loop

Each iteration Character at position 0 is read, and assigned to variable 'c', next iteration position will be incremented by 1, read it,and assigns it to 'c', This iteration process continues till the end of the string.

		name='Mark Peterson'
		
		for c in name:
		 print( c )
 	
Output:
M
a
r
k
 
P
e
t
e
r
s
o
n

For loop and Tuple object

     In Python tuple is a iterables Object and immutable Object too,so it can be used in for loop

In this example 'records' variable is a Tuple, each element in that is also a Tuple

Iterating each element in Tuple 'records' returns another tuple, which has actual data. for each iteration, one tuple at a time accessed, displayed on standard output device(sys.stdout), as shown below

		records = (
		
			( 'Sam', '$3000', 'Programmer Analyst'),
			( 'Mark', '$5000', 'CTO'),
			( 'Anderson', '$8000', 'CEO')
		
		)
		
		for rec in records:
		 print( rec )
 	
Output:
('Sam', '$3000', 'Programmer Analyst')
('Mark', '$5000', 'CTO')
('Anderson', '$8000', 'CEO')

For loop and List object

    List Object is a Sequence object, each element can be accessed using index, and also iteratable, so iteratable objects can be accessed using for loop/for-each loop

 		fish=['whale','shark','dolphin','blufish','flounder','stingray']
 	
Print fish types using for loop
 		for fish_type in fish: print(fish_type)
 	
Print fish types in reverse order using for loop
 		for fish_type in fish[::-1]: print(fish_type)
 	
Print sorted fish types using for loop
 		for fish_type in sorted(fish): print(fish_type)
 	

For loop and Set object

     Set Object is an unordered Data Structure,holding any type of data, Which implements iter method,

for loop on Set Object

		alpha=set('abcdef')
	
		for c in alpha: print(c, sep=' ',end=' ')
		print()
	

For loop and Dictionary object

    Dictionary Object is unordered data structure, which has 'key:value' pair as an element. key is immutable object,like int int,float,string,tuple, and values can be of any type. Dictionary object provides, methods for accessing exclusively keys or values, Based on keys values can be fetched.

Accessing Dictionary keys using for loop, we have 3 keys name,age and job , each key is associated with values, tuple('Jhon','Q','toe) 48,engineer respectively.

	me = {'name':('John', 'Q', 'Doe'), 'age':'48', 'job':'engineer'}
	
Only Keys
		for key in me.keys():
		   print("key is ",key)
	
Output
	key is  name
	key is  age
	key is  job
	
Only Values
		for value in me.values():
		   print("value is ",value)
	
Output
	value is  ('John', 'Q', 'Doe')
	value is  48
	value is  engineer	
	
Accessing key,value pair using for loop
 		for key in me.keys():
 		 print(key,':',me[key])
 	
Output
	name : ('John', 'Q', 'Doe')
	age : 48
	job : engineer
 	
Accessing key,value pair using items() method in for loop
 		for key,value in me.items():
 		 print(key,':',value)
 	
Output
	name : ('John', 'Q', 'Doe')
	age : 48
	job : engineer
 	

Accessing key value pair at a time from dictionary object, throws an exception ValueError. Because me returns single value at atime.

	>>> for k,v in me:
	...  print(k,v)
	... 
	Traceback (most recent call last):
	  File "", line 1, in 
	ValueError: too many values to unpack (expected 2)

items() method in dictionary returns a list , each element is a tuple, loping using items() methods. is nothing but looping through a list

 		>>>me.items
 		dict_items([('name', ('John', 'Q', 'Doe')), ('age', '48'), ('job', 'engineer')])

 	

While loop Example

   The following While loop excutes 5 times, prints on standard output device (sys.stdout ) 'Hello' text, and n is decremented by 1, exits when n is equal to 0

		n = 5;
		while n :
		    print('Hello')
		    n=n-1;
 	

While Loop with else statement

     Following While Loop executes for n number of times(n specified by user) Once loop condition fails , it executes else block of code

 		n = int( input('Pls enter number:') )
 		
 		while n > 0 :
 		   print('Hello')
 		   n -= 1 
 		
 		else :
 		   print( 'Value of n is  {0}'.format(n) )
 	

When n is 0 , else block will be executed.

While Loop with break and continue statement

     continue statement with in the while loop, skips the following statements
break statement breaks/exits from the loop

Printing first 10 Even Numbers;
n=1
print   ('Printing first 10 Even Numbers')
count=0;
while( n > 0 ):
 n=n+1
 if n%2 !=0:  continue
 count = count + 1;
 print(n,sep=' ',end=' ')
 if count == 10: break
print()
output
Printing first 10 Even Numbers
2 4 6 8 10 12 14 16 18 20 

Infinite While Loop

    Infinite loop continues execution forever, so it consumes more CPU cycles, it's execution can be stopped using 'Ctrl-C' command (or) by calling break statement on some condition with in the while loop

Simple Infinite While Loop
		while True:
		    pass
	

    The above while loop executes forever, Whenever user presses 'Ctrl-C' command, breaks the loop and raises an Exception called ,   KeyboardInterrupt Exception

The following example, While loop runs forever until user enters 'Bye' text. It reads text from standard input device(sys.stdin),assigns that value to 'name' variable, compares name with 'Bye' string(case-sensitive), if not enters into loop, prints the name, again asks/waits for user input. This loops continues execution forever,
Note:you can break this loop by issuing 'Ctrl-C' command

			name = input('Please enter your name else say Bye:');
			
			while name != 'Bye' :
			   print(name)
			   name = input('Please enter your name else say Bye:');
			   
		
		

Traceback (most recent call last): File "", line 1, in RuntimeError: Set changed size during iteration

ADS