sampleqa.in tutorial, python tutorial

Python tutorial


Python Functions

     Python supports multiple paradigms, In that Structural Paradigm, functions are core unit of work. A function is a named block of code that performs a task and returns control to the caller. A function is often executed(called) several times, in different places of the program, during execution of the program.



function syntax:
		def name_of_subroutine([optional parameters]:
			statement 1
			statement 2
			.....
			statement N
	
Calling function:
		fun();  
		fun(arg1,arg2,arg3 .... arg N)
	
Example: Function without Parameters -- fun.py

    def keyword followed by function name with no parameters. fun function has print statement

		def fun():
			print('Hello World!')
			
		fun();  //calling function
		
		-- Execute fun.py
		$python fun.py	
		Hello World!
	
Example: Function with Parameters -- add.py

    add method accepts 2 parameters, obj1 and obj2 . obj1 and obj2 are numbers, + operator performs arithmetic operation. obj1 and obj2 are strings then + operator performs string concatenation. similary for list and tuple + operator performs concatenation

		def add( obj1, obj2 ):
			return  obj1 + obj2;
			
		#calling function with different types of data	
		result1 = add( 1 , 2 )  
		result2 = add( 2.2 , 3.3 )
		result3 = add( "Hello"  ,  " World" )
		result4 = add( [1,2] , [3,4] )
		result5 = add( (1,2) , (3,4) )
		
		print( " add int objects result= " , result1 );
		print( " add float objects result=" , result2 );
		print( " concatenate string objects result=" , result3 );		
		print( " concatenate list objects result=" , result4 );
		print( " concatenate tuple objects result=" , result5 );		

		
		-- Execute add.py
		$python add.py	
		add int objects result=  3
		add float objects result= 5.5
		concatenate string objects result= Hello World
		concatenate list objects result= [1, 2, 3, 4]
		concatenate tuple objects result= (1, 2, 3, 4)

	

Problem with the above code is except numeric types, for concatenation, all other types require operands should be of same type. i.e obj1 and obj2 should be of same type.

concatenate string with number won't work, similary for tuple or list with number or string, wont's work

+ operator cannot concatenate Set and Dictionary Objects too, we need different approach to add set and dict objects


Let's modify the above add method in add.py, to add dictionary and set objects

		def add( obj1, obj2 ):
			t1 = type( obj1 )
			t2 = type( obj2 )
			if t1 == t2 and ( (isinstance(obj1 , set) and isinstance(obj2,set))
                        or (isinstance(obj1,dict) and isinstance(obj2,dict) )):
			   obj1.update(obj2);
			   return obj1;
			else:
			   return obj1 + obj2
	

Now execute the add method on set and dictionary objects

	result6 = add( {1,2}, {3,4});
	result7 = add( {1:2}, {3:4});	

	Conatenate set objects result= {1, 2, 3, 4}
	Concatenate dictionary objects result= {1: 2, 3: 4}

	

	

Python functions Part 2

ADS