cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
83 views
25 slides
May 27, 2024
Slide 1 of 25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
About This Presentation
Python functions class 12
Size: 506.92 KB
Language: en
Added: May 27, 2024
Slides: 25 pages
Slide Content
C h ap t er 2 F un c t i o n s New s y llabus 2023-24
Function Int r oduction A function is a programming block of codes which is used to perform a single, related task. It only runs when it is called. We can pass data, known as parameters, into a function. A function can return data as a result. We have already used some python built in functions like print(),etc and functions defined in module like math.pow(),etc.But we can also create our own functions. These functions are called user- defined functions.
Advantages of Using functions: Program development made easy and fast : Work can be divided among project members thus implementation can be completed fast. Program testing becomes easy : Easy to locate and isolate a faulty function for further investigation Code sharing becomes possible : A function may be used later by many other programs this means that a python programmer can use function written by others, instead of starting over from scratch. Code re-usability increases : A function can be used to keep away from rewriting the same block of codes which we are going use two or more locations in a program. This is especially useful if the code involved is long or complicated. Increases program readability : The length of the source program can be reduced by using/calling functions at appropriate places so program become more readable. Function facilitates procedural abstraction : Once a function is written, programmer would have to know to invoke a function only ,not its coding. Functions facilitate the factoring of code : A function can be called in other function and so on…
T ype s o f function s : 1.Built- in functions 2.Functions defined in module 3.User defined functions
1). Built-in Functions: Functions which are already written or defined in python. As these functions are already defined so we do not need to define these functions. Below are some built-in functions of Python. Function name Description len() list() max() min() open ( ) p r i n t() str() sum() type() tup l e() It returns the length of an object/value. It returns a list. It is used to return maximum value from a sequence (list,sets) etc. It is used to return minimum value from a sequence (list,sets) etc. It is used to open a file. It is used to print statement. It is used to return string object/value. It is used to sum the values inside sequence. It is used to return the type of object. It is used to return a tuple.
2). Functions defined in module: A module is a file consisting of Python code. A module can define functions, classes and variables. Save this code in a file named mymodule.py def greeting(name): print("Hello, " + name) Import the module named mymodule, and call the greeting function: import mymodule mymodule.greeting(“India")
3). U ser de f ine d fu n ctio n: Functions that we define ourselves to do certain specific task are referred as user-defined functions because these are not already available.
Creating & calling a Function (user defined)/Flow of execution A fun c t i on is de f ine d us i n g t he de f k e y w o r d in python.E.g. program is given below. def my_own_function(): print("Hello from a function") #program start here.program code pr i nt("hell o be f o r e cal l in g a function") my_own_function() #function calling.now function codes will be executed pr i nt("hell o af t er cal l in g a function") Save the above source code in python file and execute it #Function block/ d e f init i on/c r eation
Variable’s Scope in function The r e a r e th r ee types of v a r i a bles with the v ie w of s c ope. Local variable – accessible only inside the functional block where it is declared. Global variable – variable which is accessible among whole program using global keyword. Non local variable – accessible in nesting of functions,using nonlocal keyword. Local variable program: def fun(): s = "I love India!" #local variable print(s) s = "I love World!" fun() print(s) Output: I love India! I l o v e W o r ld! Global variable program: def fun(): global s #accessing/making global variable for fun() print(s) s = " I l o v e I n d i a!“ #c h angi n g g lo b al v ariabl e ’ s v alue print(s) s = " I l o v e w o r l d !" fun() print(s) Output: I l o v e w o r ld! I love India! I love India!
Variable’s Scope in function #Find the output of below program de f fu n (x, y) : # a r gument / pa r ame t er x and y global a a = 10 x,y = y,x b = 20 b = 30 c = 30 print(a,b,x,y) a, b, x, y = 1, 2, 3,4 fu n (50, 100) # passing v alue 50 and 100 i n pa r ame t er x and y of function fun() print(a, b , x , y V ) isit : p ytho n . m y k v s . i n f or r egu l ar upda t es
Variable’s Scope in function # F i n d th e o u t p u t of bel o w p r og r am def fun(x, y): # argument /parameter x and y global a a = 10 x,y = y,x b = 20 b = 30 c = 30 print(a,b,x,y) a, b, x, y = 1, 2, 3,4 fun(50, 100) #passing value 50 and 100 in parameter x and y of function fun() print(a, b, x, y) OUTPUT :- 10 30 100 50 10 2 3 4
Variable’s Scope in function Global variables in nested function def fun1(): x = 100 def fun2(): global x x = 200 print("Before calling fun2: " + str(x)) print("Calling fun2 now:") fun2() p rint("A f t er callin g fun2: " + str(x ) ) fun1() print("x in main: " + str(x)) OUTPUT: Bef o r e callin g fun2: 100 Calling fun2 now: A f t er callin g fun2: 1 00 x in main: 200
Variable’s Scope in function Non local variable def fun1(): x = 100 def fun2(): nonlocal x #change it to global or remove this declaration x = 200 print("Before calling fun2: " + str(x)) print("Calling fun2 now:") fun2() p rint("A f t er callin g fun2: " + str(x ) ) x=50 fun1() print("x in main: " + str(x)) OUTPUT: Be f o r e cal l in g fun2: 100 Calling fun2 now: Af t er cal l in g fun2: 200 x in main: 50
F unction Parameters / Arguments Passing and return value These are specified after the function name, inside the parentheses. Multiple parameters are separated by comma.The following example has a function with two parameters x and y. When the function is called, we pass two values, which is used inside the function to sum up the values and store in z and then return the result(z): def sum(x,y): #x, y are formal arguments z=x+y r eturn z # r et u r n th e v alue/ r esult x,y=4,5 r=sum(x,y) #x, y are actual arguments print(r) N o t e :- 1 . F uncti o n P r o t ot yp e i s de c la r ati o n o f f uncti o n w i t h name ,argument and return type. 2. A formal parameter, i.e. a parameter, is in the function definition. An actual parameter, i.e. an argument, is in a function call.
F unction Function Arguments Functions can be called using following types of formal arguments − Required arguments/ Positional parameter - arguments passed in correct positional order Keyword arguments - the caller identifies the arguments by the parameter name Default arguments - that assumes a default value if a value is not provided to argu. Variable-length arguments – pass multiple values with single argument name. #Required arguments def square(x): z=x*x return z r=s qua r e() print(r) #In above function square() we have to definitely need to pass some value to argument x. # K e y w o r d a r g u ments def fun( name, age ): "This prints a passed info into this function" print ("Name: ", name) print ("Age ", age) return; # N o w y ou ca n ca l l pri n t i n f o fu n c t i on fun( age=15, name="mohak" ) # value 15 and mohak is being passed to relevant argument based on keyword used for them.
F unction #Default arguments / #Default Parameter def sum(x=3,y=4): z=x+y return z r=sum() print(r) r=sum(x=4) print(r) r=su m(y= 4 5) print(r) #default value of x and y is being used when it is not passed #Variable length arguments def sum( *vartuple ): s=0 f or v ar i n v artupl e : s=s+int(var) r eturn s; r=sum( 70, 60, 50 ) print(r) r=su m( 4 ,5) print(r) #n o w th e ab o v e functi o n su m () can sum n numbe r of v alues
L amda Python Lambda A lambda function is a small anonymous function which can ta k e a n y n umbe r of a r gument s , b u t ca n o n l y h a v e o n e expression. E.g. x = lambda a, b : a * b print(x(5, 6)) OUTPUT: 30
Mutable/immutable properties of data objects w/r function Everything in Python is an object,and every objects in Python can be either mutable or immutable. Since everything in Python is an Object, every variable holds an object instance. When an object is initiated, it is assigned a unique object id. Its type is defined at runtime and once set can never change, however its state can be changed if it is mutable. Means a mutable object can be changed after it is created, and an immutable object can’t. Mutable objects: list, dict, set, byte array Immutable o b j e ct s : in t , f loat, c omp l ex, s t r in g , tup l e, frozen set ,bytes
M ut a ble/immu tab l e p r oper t i es of data objects w/r function How objects are passed to Functions #Pass by reference def updateList(list1): p r i n t( i d( l ist1)) list1 += [10] p r i n t( i d( l ist1)) n = [50, 60] print(id(n)) u pda t e Li s t ( n ) print(n) print(id(n)) OUTPUT 34122928 34122928 34122928 [50, 60, 10] 34122928 #In above function list1 an object is being passed and its contents are changing because it is mutable that’s why it is behaving like pass by reference # P ass b y v al u e def updateNumber(n): print(id(n)) n += 10 p r i n t( i d( n )) b = 5 print(id(b)) u pda t e N u mbe r (b) print(b) print(id(b)) OUTPUT 1691040064 1691040064 1691040224 5 1691040064 #In above function value of variable b is not being changed because it is immutable that’s w h y i t i s b eh a ving l i k e p ass b y v alue
Functions using libraries Mathematical functions: Mathematical functions are available under math module.To use mathematical functions under this module, we have to import the module using import math. F or e . g . To use sqrt() function we have to write statements like given below. import math r =mat h . sq r t( 4 ) print(r) OUTPUT : 2.0
Functions using libraries Functions available in Python Math Module
Functions using libraries (System defined function) String functions: String functions are available in python standard module.These are always availble to use. F or e. g . capi tali z e() function C o nv er t s th e f i r st cha r ac t er of str i n g t o uppe r cas e . s="i love programming" r=s.capitalize() print(r) OUTPUT: I love programming
Functions using libraries String functions: Method Description capitalize() C o n v e r ts the f irs t cha r ac t er t o uppe r case casefold() C o n v e r ts st r i n g i n t o l o w er case center() Returns a centered string count() Returns the number of times a specified value occurs in a string encode() Returns an encoded version of the string endswith() Returns true if the string ends with the specified value find() Searches the string for a specified value and returns the position of where it was found format() Formats specified values in a string index() Searches the string for a specified value and returns the position of where it was found
Functions using libraries String functions: Method Description isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isdecimal() Returns True if all characters in the string are decimals isdigit() R eturns T r u e i f all cha r ac t e r s i n the st r i n g a r e d i g i ts isidentifier() Returns True if the string is an identifier islower() R eturns T r u e i f all cha r ac t e r s i n the st r i n g a r e l o w er case isnumeric() Returns True if all characters in the string are numeric isprintable() Returns True if all characters in the string are printable isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case join() Joins the elements of an iterable to the end of the string ljust() Returns a left justified version of the string lower() C o n v e r ts a st r i n g i n t o l o w er case lstrip() Returns a left trim version of the string partition() Returns a tuple where the string is parted into three parts
Functions using libraries String functions: Method Description replace() Returns a string where a specified value is replaced with a specified value split() Splits the string at the specified separator, and returns a list splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value swapcase() S w aps case s , l o w er cas e be c omes uppe r cas e and v i c e v e r sa title() C o n v e r ts the f irs t cha r ac t er of each w o r d t o uppe r case translate() Returns a translated string upper() Converts a string into upper case zfill() F i l ls the st r i n g with a speci f ie d n u m b er of v al u es at the beg i n n i n g