User Defined Functions in Python
Functions in Python
A function is a group of statements that perform a specific task. A function executes when it is called.
Advantages of Functions in Python
- Program development made easy and fast.
- Program testing becomes easy.
- Re-usability of code increases.
- Reduced length of program.
Functions can be categorized into the following three types:
- Built in Functions
- Modules
- User Defined Functions
Built in Functions :
Those functions which are already available in python is called built-in functions. These are always available in the standard library. We don’t have to import any modules to use such built-in functions. Let we discuss bult-in functions in python
1. int()
This function converts any value(string or float) into an integer value. for example
>>>int('123') 123 >>>int(23.34) 23 >>>int(-56.23) -56 >>>int("CSIP") above statement returns Value Error >>>int() 0
NOTE: This function converts the floating point number to integer without rounding off. It simply removes the decimal part.
User Defined Functions in Python
2. float()
This function converts integers into floating point numbers. for example
>>>float(21) 21.0 >>>float("12.325") 12.325 >>>float("CSIP") above statement return Value Error >>>float(148.23) 148.23 >>>float() 0.0
3. input()
This function help to accept any value from the user through keyboard. This function always return a string value which can be converted into integer using int( ) functions. for example
n1 = input("Enter any number : ") print(n1) OUTPUT: Enter any number : 9 9 -------------------------------------------------------------- n1 = input("Enter any number : ") print(n1 + 3) OUTPUT: Enter any number : 5 TypeError # as input function returns a string. ------------------------------------------------------------- n1 = int(input("Enter any number : "))#using int() function to convert string to integer print(n1 + 3) OUTPUT: Enter any number : 8 11
4. eval()
This function takes the string value and evaluates. If the argument is not string then eval( ) function returns an error. for example
>>>eval('2' + '6') 26 >>>eval('3' + '5') 8 >>>eval(3 + 8) Type Error
User Defined Functions in Python
5. max()
This function returns the largest value out of the given arguments. for example
>>>max(6, 9, 12, 32) 32 >>>max(23, 3.45, 67, 12.4) 67 >>>max('d', 5, 7.8, 9) Type Error #String and Integer can not be compared >>>max('a', 'b', 'f', 'j') #it returns the largest value according to ASCII value 'j ' >>>max("Amit", "Raj", "Raman", "Zafar") 'Zafar'
6. min()
This function returns the smallest value out of the given arguments. for example
>>>min(1, 2, 3, 4) 1 >>>min(10.5, 2.9, 3, 4) 10.5 >>>min('a', 'b', 'f', 'j') #it returns the smallest value according to ASCII value 'a' >>>min(10.5, 2.9, 3, 4, 5*2-8) 2 >>>min('a', 'b', 'f', 'j', 8, 90, 12) Type Error #String and Integer can not be compared
NOTE: ASCII value of ‘A’ is 65 and ‘a’ is 97
7. abs()
This function always return an absolute value(positive value) of a number. for example
>>>abs(34) 34 >>>abs(-56.7) 56.7 >>>abs( ) TypeError: abs() takes exactly one argument (0 given) >>>abs(78-100) 22
User Defined Functions in Python
8. type()
This function returns the data type of a variable or a value. In other words we can say that it simply returns the type of value hold by a variable. for example
>>>type(25) <class 'int'> >>>x =7.6 >>>type(x) <class 'float'> >>>type('True') <class 'str'> >>>type(True) <class 'bool'>
9. len()
This function return the total number of items in an object. The object may be String, tuple, list etc. for example
>>>len((1, 3, 45, 32, 'a')) 5 x = [12, 32, 43, 11, 21, 89] >>>len(x) 6 >>>len(45, 67, 32) TypeError: len() takes exactly one argument (3 given)
10. range()
This function generates a sequence of number. This function is mainly used with ‘for’ loop. for example
>>>range(4) range(0, 4) The above function generates a series of number from 0 to 3. Syntax: range(Start, end, step) By default value of start is 0 and value of step is 1 >>> range(1, 9, 2) The above function generates four values ie (1, 3, 5, 7). To see the output of above function, execute the following statement. >>>list(range(1, 9, 2)) [1, 3, 5, 7]
Modules : Click for Notes
User Defined Functions :
A set of statement that performs a specific task is called function. A function which is defined or created by the user is called user defined function.
A user defined function is created by the def keyword followed by function name, parenthesis and colon.
Syntax of User Defined Function
def myfunc(p1, p2, ...) : In above statement 1. def is a keyword used to define the function. 2. myfunc is the name of the function 3. P1, P2 are the parameters. These are optional
Let we do some Practical Task
Task 1: Create a function which will print “Hello World”
def hello_func( ): #Starting of a function print("Hello World") hello_func( ) #Calling a function OUTPUT: Hello World NOTE: The above function is not returning any value. Such functions are called void functions
Task 2: Create a function which will print “Computer Science” and Informatics Practices in different lines.
def display( ): print("Computer Science") print("Informatics Practices") dislay() #Calling a function OUTPUT: Computer Science Informatics Practices
Return Statement in User Defined Function
Return statement specifies what value to be returned to the calling function. Function takes input through parameters and return the output after processing.
Task 3: Create a function which will take side of a square as parameter and return the area.
def area(side): ar = side * side return(ar) #After calculation, it is returning the value of area to the calling function a=area(7) print("Area of a Square is : ", a) OUTPUT: Area of a Square is : 49
Task 4: Write a function which will take two numbers as parameter and return the added value.
def add(n1, n2): sum = n1 + n2 return(sum) a=add(7, 9) print("Sum of the numbers are : ", a) OUTPUT: Sum of the numbers are : 16
Task 5: Write a function which will take two numbers as parameter and return the addition, difference, product and division.
def math_operations(n1, n2): sum = n1 + n2 diff = n1 - n2 mul = n1*n2 div = n1/n2 return(sum,diff,mul,div) #A function can return multiple values a=math_operations(9, 3) print("Result of operations are : ", a) #we can also display result using loop for i in a: print(i) OUTPUT: Result of operations are : (12, 6, 27, 3.0) 12 6 27 3.0
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(n1, n2): #n1 and n2 are called Formal Parameters sum = n1 + n2 return(sum) a=add(7, 9) #7 and 9 are Actual Arguments print("Sum of the numbers are : ", a)
Types of Arguments in Functions
There are following types of actual arguments:
1. Positional arguments
When we pass the actual arguments in the same order/sequence as given in the function header is called positional arguments. for example
def Vol_cuboid(L, B, H) #Function header Vol_cuboid(20, 15, 10) #Function Calling Statement In the above call the value of L will be 20, value of B will be 15 and value of H will be 10. So arguments are assigned to the parameters according to their position.
2. Default arguments
Those arguments which will assign default value if the value is not provided in the function call.
NOTE: Default argument should not come after non-default arguments
Following are the valid function header def SI(Pr, R, T=3): def add(a, b=2, c=9): def display(p, q, r, s=9): Following are invalid function header def SI(Pr, R=7, T): def add(a, b=2, c): def display(p, q=5, r, s=9):
def func(p, q=15, r=5): print('p is', p, 'and q is', q, 'and r is', r) func(5, 8) func(15, r = 24) func(r = 40, p = 50) OUTPUT: p is 5 and q is 8 and r is 5 p is 15 and q is 15 and r is 24 p is 50 and q is 15 and r is 40
NOTE: If we are not passing any value to an argument, then default value will be assigned. If we are passing a value then this value over write the default value.
3. Keyword arguments
In a function call, we can specify the values of arguments using their names instead of their position or order. These are called Keyword or Name arguments.
def message(rno, name, clas): print("Your Roll Number is : ", rno) print("Your Name is : ", name) print("Your Class is : ", clas) message(name="Amit", clas=12, rno=7) #Here we are passing by name not by position OUTPUT: Your Roll Number is : 7 Your Name is : Amit Your Class is : 12
Practice Exercise
Q1. Write the output of the following Code
value = 10 def disp(s): global value value = 5 if s%7==0: value = value + s else: value = value - s print(value, end="?") disp(49) print(value)
OUTPUT
54?54
Q2. Write the output of the following Code
def func(p, q=15, r=5): print('p is', p, 'and q is', q, 'and r is', r) func(5, 8) func(15, r = 24) func(r = 40, p = 50)
OUTPUT
p is 5 and q is 8 and r is 5
p is 15 and q is 15 and r is 24
p is 50 and q is 15 and r is 40
Q3. Write the output of the following Code.
c = 12 def show(): global c c = c + 12 print("Inside show():", c) show() c=10 print("In main:", c)
OUTPUT
Inside show(): 24
In main: 10
Q4. Write the output of the following Code.
def List(D): ct = 3 tot = 0 for C in [7,5,4,6]: T = D[ct] tot = float(T) + C print(tot) ct-=1 L = ["10","15","20","25"] List(L)
OUTPUT
32.0
25.0
19.0
16.0
Q5. Write the output of the following Code.
s = 3 def get(): global s s = s+10 def findArea(): Ar = s * s print("Area = ", Ar) get() findArea()
OUTPUT
Area = 169
Q6. Write the output of the following Code.
def act(x): a=5 b=15 for i in range(2,x//2): if x%i==0: if a is None: a = i else: b = i break return a,b S=act(3) print(S)
OUTPUT
(5, 15)
Q7. Write the output of the following Code.
def convert(s): k=len(s) m="" for i in range(0,k): if(s[i].isupper()): m=m+s[i].lower() elif s[i].isalpha(): m=m+s[i].upper() else: m=m+'c' print(m) convert('exam@2023')
OUTPUT
EXAMccccc
Q8. Write the output of the following Code.
def seq(x=11, y=12): x = x+y y+=2 print(x, '#', y) return x,y a,b = seq() print(a, '&', b) seq(a,b) print(a+b)
OUTPUT
23 # 14
23 & 14
37 # 16
37
Q9. Write the output of the following Code.
def Val(M,N): for i in range(N): if M[i]%5 == 0: M[i] //= 7 if M[i]%3 == 0: M[i] //= 3 L=[21,8,75,12] Val(L,4) for i in L : print(i, end='#')
OUTPUT
7#8#10#4#iIFforAaIcs
Q10. Write the output of the following Code.
def stringresult(s): n = len(s) m='' for i in range(0, n): if (s[i] >= 'a' and s[i] <= 'k'): m = m + s[i].upper() elif (s[i] >= 'l' and s[i] <= 'z'): m = m + s[i-1] elif (s[i].isupper()): m = m + s[i].lower() else: m = m + '#' print(m) stringresult('InformatiCS') #Calling
OUTPUT
iIFforAaIcs
Q11. Write the output of the following Code.
def Convert(m, n = 40) : m = m + n n = m - n print (n,"?",m) return n r =100 s= 70 r=Convert(r, s) print(s,"\\",r) s=Convert (s)
OUTPUT
100 ? 170
70 \ 100
70 ? 110
User Defined Functions in Python
User Defined Functions in Python
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 correct notes of ”User Defined Functions in Python“ , but if you feel that there is/are mistakes in the Notes of ”User Defined Functions in Python“ You can directly contact me at csiplearninghub@gmail.com. The above Notes are created from NCERT Book.