Chapter 7 Functions of Python Class 11 Notes Important Points
Chapter 7 Functions of Python Class 11 Notes
Functions in Python
Function can be defined as a named group of instructions that perform a specific task when it is invoked. Once
defined, a function can be called repeatedly from different places of the program, or it can be called from inside another function, by simply writing the name of the function and passing the required parameters, if any.
Advantages of Functions in Python
- Program development made easy and fast.
- Program testing becomes easy.
- Re-usability of code increases.
- Reduced length of program.
User Defined Functions :
Those functions which are defined to achieve some task as per the programmer’s requirement is called a user defined function.
Creating User Defined Functions :
A function definition begins with def (short for define). The syntax for creating a user defined function is as follows:
def myfunc(p1, p2, ...) : #Function header statements to be executed return <value>
In above code 1. def is a keyword used to define the function. 2. Function header always ends with a colon (:) 3. Function name should be unique. 4. myfunc is the name of the function 5. P1, P2 are the parameters. These are optional
Example 1: Write a user defined function to add two numbers and display their sum.
def sum2num(): n1 = int(input("Enter first number: ")) n2 = int(input("Enter second number: ")) s = n1 + n2 print("The sum is ",s) #function call sum2num() NOTE: Function can be called in the program by writing function name followed by () as shown above
Example 2: Write a user defined function “rec_ar” to calculate the area of rectangle.
def rec_ar(): L = int(input("Enter length of rectangle: ")) B = int(input("Enter breadth of rectangle: ")) A = L * B #Area of rectangle = length * breadth print("The area of rectangle is ",A, "sq. units") #function call rec_ar()
Parameters and Arguments in Functions
Parameters are the variables which we write in the parenthesis after the function name in the function header. for example
def calculate(x, y) #Here x and y are called Formal Parameters
An argument is a value which we passed to a function through function calling statement. Such arguments are called Actual Parameters or Actual Arguments.
def add(a, b): #n1 and n2 are called Formal Parameters sum = a + b return(sum) p=add(7, 9) #7 and 9 are Actual Arguments print("Sum of the numbers is : ", p)
Example 3: Write a user defined function “sqnum” which accept an integer as an argument and display it’s square.
def sqnum(num1): #num1 is a parameter print("Square of a number is : ", num1 * num1) n1 = int(input("Enter any number")) sqnum(n1) #n1 is an argument.
Example 4: Write a user defined function strwords( ) which takes string as an argument and display total number of words.
def strwords(st1): c = 0 l = st1.split() for i in l: c = c+1 print("Total number of words : ", c) str1 = input("Enter any string: ") strwords(str1) OUTPUT: Enter any string: My name is Amit Total number of words : 4
Example 5: Write a user defined function “listsum” which takes a list containing five numbers as an argument and display the sum of all the numbers.
def listsum(Lst): s=0 for i in Lst: s = i+s print("Sum of all numbers is : ", s) L = [3, 2, 8, 5, 4] listsum(L) OUTPUT: Sum of all numbers is : 22
Example 6: Write a program which takes a number as an argument and display it’s factorial.
def fact(num1): if num1==0: print("Factorial is : 1") else: f=1 for i in range(1, num1+1): f = f*i print("Factorial of a number is : ", f) n1 = int(input("Enter any number : ")) fact(n1) OUTPUT: Enter any number : 6 Factorial of a number is : 720
Example 7: Write a user defined function join_name() that accepts the first name and last name as arguments, and concatenate them to get full name.
def join_name(fn, ln): fullname = fn + ln print(fullname) fname = input("Enter first name : ") lname = input("Enter last name : ") join_name(fname, lname) OUTPUT: Enter first name : Parth Enter last name : Sethi ParthSethi
Example 8: Write a user defined function avg( ) which takes three numbers as an argument and display the average of them. If two numbers are passed as an argument then the third number will be taken as 9(default parameter)
def avg(n1, n2, n3=9): avr = (n1+n2+n3)/3 print("Average is ", avr) avg(6, 9, 3) avg(2, 7)#default value of third number OUTPUT: Average is 6.0 Average is 6.0
Important Points to remember about function
- A function argument can also be an expression. like avg(n1, n2+2, n3*2)
- The parameters should be in the same order as that of the arguments
- The default parameters must be the trailing parameters in the function header like
- avg(n1, n2, n3=4)
- avg(n1, n2=4, n3=40)
- avg(n1, n2=5, n3) #wrong function call
Example 9: Identify the wrong function definition header given below. Also correct them also
- def sum(a =9, b, c=10):
- def SI(P=1000, R=4, T):
- def area(l, b, h=3):
- def vol(a, b=9, c):
Ans. 1, 2 and 4 are wrong, their correct forms is given below.
- def sum(b, a =9, c=10): #default parameters must be at the end
- def SI(T, R=4, P=1000):
- def vol(a, c, b=9):
Return Statement in function :
The return statement returns the values from the function. In the examples given above, the function performs calculations and display result(s).They do not return any value. Such functions are called void functions. But a situation may arise, wherein we need to send value(s) from the function to its calling function.
Example 10: Write a user define function pow( ) which takes base and exponent as argument and return the result base exponent
def pow(b, e): res=1 for i in range(1, e+1): res=res*b return res base = int(input("Enter base : ")) exp = int(input("Enter exponent : ")) ans = pow(base,exp) print("Result is : ",ans) OUTPUT: Enter base : 3 Enter exponent : 4 Result is : 81
In Python, we can have the function in either of the following ways:
- Function with no argument and no return value
- Function with no argument and with return value(s)
- Function with argument(s) and no return value.
- Function with argument(s) and return value(s)
Flow of execution :
Flow of execution can be defined as the order in which the statements in a program are executed. when the interpreter encounters a function call, the control jumps to the called function and executes the statement of that function. After that, the control comes back the point of function call so that the remaining statements in the program can be executed.
When we call a function call before the function definition, the interpreter does not find the function definition and hence raised an error. for example
hello( ) def hello( ): print("Hello") OUTPUT: NameError: name 'hello' is not defined
There will be no error when the function definition is made before the function call as shown below:
def hello( ): print("Hello") hello( ) OUTPUT: Hello
Following code explains the flow of execution of statement in a program. The number in square brackets shows the order of execution of the statements.
[5] def vol(l,b,h): [6] V = l*b*h [7] return V [1] L = int(input("Enter length of Cuboid")) [2] B = int(input("Enter breadth of Cuboid")) [3] H = int(input("Enter height of Cuboid")) [4],[8] res = vol(L,B,H) [9] print("Volume of Cuboid is : ",res)
NOTE: Function can return multiple values through tuple. for example
def vol(l,b,h): V = l*b*h TSA = 2*(l*b +b*h +h*l) return (V, TSA) L = int(input("Enter length of Cuboid : ")) B = int(input("Enter breadth of Cuboid : ")) H = int(input("Enter height of Cuboid : ")) volume, surarea = vol(L,B,H) print("Volume of Cuboid is : ",volume) print("Total Surface area of Cuboid is : ",surarea) OUTPUT: Enter length of Cuboid : 5 Enter breadth of Cuboid : 4 Enter height of Cuboid : 3 Volume of Cuboid is : 60 Total Surface area of Cuboid is : 94
Scope of a Variable
The part of the program where a variable is accessible can be defined as the scope of that variable. A variable can have one of the following two scopes:
1. Global Variable: A variable that is defined outside any function or any block is known as a global variable. It can be accessed in any functions defined onwards.
2. Local Variable: A variable that is defined inside any function or a block is known as a local variable. It can be accessed only in the function or a block where it is defined. It exists only till the function executes.
Example to show the concept of Global and Local variable is given below
num=4 def scope( ): y = 6 print("Global Variable : ", num) print("Local Variable : ",y) print("Global Variable outside function : ", num) #global variable is accessible through out the program. scope( ) print("Local Variable outside function : ", y) #return error as we access local variable outside function OUTPUT: Global Variable outside function : 4 Global Variable : 4 Local Variable : 6 Traceback (most recent call last): File "C:/Users/admin/AppData/Local/Programs/Python/Python37/test.py", line 8, in <module> print("Local Variable outside function : ", y) NameError: name 'y' is not defined
Accessing Global variable inside a function by using keyword ‘global’
n=4 def scope(): global n n=7 print(n) scope() print(n) OUTPUT: 7 7
Python Standard Library :
Python Standard library is a collection of many built in functions that can be called in the program as and when required.
Built in Function of Python :
Built-in functions are the ready-made functions of Python that are frequently used in programs. Let us check the following Python program:
#addition of two numbers num1 = int(input("Enter first number")) num2 = int(input("Enter Second number")) res = num1 + num2 print("Answer is : ", res)
In the above program int(), input() and print() are the built-in functions. The set of instructions to be executed for these built-in functions are already defined in the python interpreter.
Following is a categorised list of some of the frequently used built-in functions in Python:
1. Input or Output :
a. input() : This function is used to accept input from the user. for example
nm = input(“Enter your name”)
b. print() : This function is used to display any message or data on the screen.
print(“Hello World”)
OUTPUT:
Hello World
2. Mathematical Function :
Function Name | Description | Example |
abs(x) | It returns the absolute value of x. | >>>abs(3) 3 >>>abs(-7) 7 >>>abs(-3.4) 3.4 |
divmod(m,n) | It returns quotient and remainder both in the form of tuple when m is divided by n. | >>>divmod(9,2) (4,1) >>>divmod(15,4) (3,3) |
max(sequence) | It returns the largest number from the sequence. | >>>max([3, 7, 4, 9]) 9 >>>max([9, 10, 34, 3.5, 41.5]) 41.5 >>>max(100, 78, 123, 91, 210) 210 |
min(sequence) | It returns the smallest number from the sequence. | >>>min([23, 41, 12, 9]) 9 >>>min(34, 67, 98, 12) 12 |
pow(x,y[,z]) Third argument z is optional. | It returns xy (x raised to the power y) if z is provided, then it will return (xy ) % z | >>>pow(2,3) 8 >>>pow(2, 6, 5) 4 |
sum(x, num) x is a sequence and num is an number | It returns the sum of all the numbers in a sequence and the number given outside the sequence. | >>>sum([1,2,3,4], 8) 18 |
len(x) | It returns the total number of elements in the sequence. | >>>len([3, 4, 6, 1, 8, 0]) 6 >>>len(“Computer”) 8 >>>len({‘A’ : “Apple”, ‘B’ : “Ball”, ‘C’ : “Cat”}) 3 |
Click for Notes : Modules in Python
SUMMARY 1. In programming, functions are used to achieve modularity and reusability. 2. Function can be defined as a named group of instructions that are executed when the function is invoked or called by its name. Programmers can write their own functions known as user defined functions. 3. The Python interpreter has a number of functions built into it. These are the functions that are frequently used in a Python program. Such functions are known as built-in functions. 4. An argument is a value passed to the function during function call which is received in a parameter defined in function header. 5. Python allows assigning a default value to the parameter. 6. A function returns value(s) to the calling function using return statement. 7. Multiple values in Python are returned through a Tuple. 8. Flow of execution can be defined as the order in which the statements in a program are executed. 9. The part of the program where a variable is accessible is defined as the scope of the variable. 10. A variable that is defined outside any particular function or block is known as a global variable. It can be accessed anywhere in the program. 11. A variable that is defined inside any function or block is known as a local variable. It can be accessed only in the function or block where it is defined. It exists only till the function executes or remains active. 12. The Python standard library is an extensive collection of functions and modules that help the programmer in the faster development of programs. 13. A module is a Python file that contains definitions of multiple functions. 14. A module can be imported in a program using import statement. 15. Irrespective of the number of times a module is imported, it is loaded only once. 16. To import specific functions in a program from a module, from statement can be used
Class 11 : NCERT Solutions
Ch5 : Getting Started with Python
Ch10 : Tuples and Dictionaries
MCQ of Computer Science Chapter Wise
2. Flow of Control (Loop and Conditional statement)
3. 140+ MCQ on Introduction to Python
4. 120 MCQ on String in Python
7. 100+ MCQ on Flow of Control in Python
8. 60+ MCQ on Dictionary in Python
Important Links
100 Practice Questions on Python Fundamentals
120+ MySQL Practice Questions
90+ Practice Questions on List
50+ Output based Practice Questions
100 Practice Questions on String
70 Practice Questions on Loops
70 Practice Questions on if-else
Disclaimer : I tried to give you the simple ”Functions of Python Class 11 Notes” , but if you feel that there is/are mistakes in the code or explanation of “Functions of Python Class 11 Notes“ given above, you can directly contact me at csiplearninghub@gmail.com. Reference for the notes is NCERT book. The content of this article is from NCERT book Rationalised syllabus.
Best best best..
Thnnnxxx.