Topic : Function
Function - A large program is divided into small module . These modules are known as functions.
Advantage of function – 1. Program handling is easier 2. Function can be defined once and used
many time. 3. Function code is written once and called from any part of the program.
There are 3 types - 1. Build in function 2. Modules 3. User defined function
Build in function – Predefined function that are already present in python
Type conversion function - int(), float(), str()
1. Int():- It takes any value and convert into integer . It does not round off it chops up the fractional
part. Ex. int(‘123’) → output is 123 integer , int(334.56) → 334 ( chop off .56) , int(-32.2) → -32
2. float():- It converts integer and string to floating number ex. float(26) → 26.0 , if the argument is
expression float(2+3) → 5.0 , float(‘3.19’) → 3.19 , float(‘86.7-‘) → error
3. input()- It takes input from keyboard and returns a string a=input(‘Enter no :’) →’56’
4. eval():- It takes string as argument , evaluate and returns the numeric result according to nature
Eval(‘2+3’) → It returns 5 , eval(2.0+3) → it returns 5.0
Ex. max(9,12,7,0) → 12 , max(‘Delhi’,’ujjain’,’Mumbai’,’Surat’) → it returns Ujjain ( it takes ascii
comparison)
Min():- It takes two or more arguments and returns the smallest item
Ex. min(-23,109,5,2) → -23
6. abs() → It returns the absolute value of single number. It takes integer or float number as an
argument and always returns a positive value
>> abs(-50) → 50 , abs(-30.6) → 30.6
7. type()- It determines the data type of the variable type(10) → class <int>
8. round() ( imp for boards):- It round the number to the specific number of decimal places and
return the result. By default round() rounds the number to zero decimal places It has two arguments
Round(n,p) n is the number / expression to be rounded and p is the number of digit up to which n
is to be rounded.
Rule – 1. P is not specified n is rounded up to 0 digit and the result is an integer
Round(12.452) → returns 12
2. if the decimal number is 5 or more than 5 the number is increased by one
Round(12.534) returns 13
3. if p is zero . It is rounded up to 0 digit and the result is in float value
Round (12.452,0) returns 12.0
Round(12.534,0) returns 13.0
4. p is positive integer n is rounded up to p by checking (p+1)th. Digit. If it is 5 or >5 then pth. Digit is
increased by 1 and the result is a float.
Round(12.452,1) → returns 12.5
Round(12.534,2) → returns 12.53
5. if p is negative integer n is rounded up to p digits before the decimal . The trailing p digits are
rounded off to 0 in case of negative value
Round(12.234.56,-1) → 1230.0
Round( 1258.4, -2) → returns 1300.0
Range() – It is define a series of number ex. range(5) → range(0,5)
Module – A module is a file containing function and variable defined in separate file . Set of
instruction stored in a file called module and the approach is called modularization its extension is
.py file.
Libraries – When we break a program into module Each module should contains a function that
perform a related task. There are some common module that are used for certain predefined task is
called libraries.
Command to import module name - import < module name > ex. import math
Command to Import all methods from module name – from < module name> import *
From math import *
Command to import sqrt method from math module - from math import sqrt
Functions under math module – ceil(), floor(),pow(),fabs(),sqrt(), log10(x) cos (x), sin(x), tan(x)
1. ceil(x) → It returns the closest integer that is greater than or equal to x
Math.ceil(3.4)) → 4
Math. Ceil(-67.8) → -67
2. floor(x) → returns the closest integer that is less than or equal to x
Math.floor(100.12) → 100.0
Math.floor(-45.17) → -46.0
3. power(x,y) → It returns the value xy . where x,y are numeric expression and function returns float
value ex. math.pow(3,3) → 9.0
4. fabs()→ It returns the absolute value ( positive value ) if the argument is integer it returns floating
point number
Import math
>> math.fabs(-15) → 15.0
5. sqrt():- It returns the square root of x ex. math.sqrt(65) → 8.06
Math.sqrt(-6) → value error
6. log10(x) → It returns the base 10 logarithm of x math.log10(100) →2.0
Random module –
Import random module → import random
Randrange()- It generate an integer between lower and upper argument by default lower argument
is 0 and upper argument is range -1
Ex to generate random number from 0 to 29 ( 30 is excluded)
Import random
T= random.randrange(30)
To generate random number from range 10 to 1000 , multiple of 5
Import random
Val = random.randrange(10,100,5) → # randrange(start, stop, step)
Random()- It generate random number from 0 to 1 . It generate random number from 0 to 1 It is
used to generate random floating value [0.1 ,1.0) Including 0 but exclude 1
Generate a number between 10 to 15
Import random
r=random.random()*5+10
Print(r)
Randint():- It accept two parameters a, b ex. random.randint(a,b) where a<=N<=b
Import random
Print(random.randint(0,9))
Uniform():- It returns a random floating number between two numbers
Random .uniform (x,y)
Ex. random.uniform(1,100)
Choice():- It is used to take random selection from list , tuple or string
Ex. import random
D=random.choice([‘east’,’west’,’north’,’south’])
Print(D)
Shuffle():- It is used to swap the content of list
Import random
Fruit = [‘apple’,’orange’,’banana’,’pineapple’,’appricot’]
Random.shuffle(fruit)
Print(fruit)
[‘appricot’,’apple’,’orange’,pinapple’,’banana’]
Parameters and argument in a function –
Parameter – It is defined by the variables provided in the parenthesis when we write function
definition It is also called formal parameter def test(p,s,i) here p, s, I are formal parameter
Argument – A value that is passed to the function when it is called is called argument . These
arguments are called actual parameter ex. test(40000,30,5)
Types of argument ( imp for boards )-
Def f1(x,y): → formal argument
……….
F1(20,30) → actual argument
There are 4 types of argument
1. Positional argument – Positional arguments are arguments passed to the actual arguments of a
function in correct positional order.
Def subtract(a,b):
Print( a-b)
Subtract(200,300) # a gets 200 and b gets 300
2. default argument – A default argument is a argument can assign a default value in a function
definition ex. def test ( principal, rate, time=2) → time is default argument
Rule – positional argument must appear before the default argument so def test( principal ,
rate=8.5, time) is wrong it creates syntax error
3. Keyboard( name) arguments – We can pass argument values by keyboard ( by parameter name)
It is also called named argument.
Def test(name, msg);
Print( name, msg)
Test(name=’vijay’, msg=’good morning’) ( keyboard argument are the named argument with
assigned values being passed in the function call )
Rule - first specify positional argument, then keyboard argument
4. Variable length argument – We can pass variable number of argument to the function . It is called
variable length argument . It is declared with * symbol
Def sum(*n);
Total =0
For I in n :
Total =total + I
Sum(20)
Sum(20,30)
Scope of a variable ( imp in boards):- It holds the current set of variables and values. There are two
types of variable scope –
1. Global module – 1 Name is assigned at the top of a module it means it is declared outside the
function. 2. Name is declared with keyword global 3. It can be assigned inside or outside the
function.
2. Local function - 1. Name is assigned inside a function 2. It can be assigned outside the function.
Rule - We can access global variable in the absence of local variable with the same name
a=2
def f(x):
y=x+a
return y
p=f(5)
print(p)
output is 7
Rule – We can use same name in different scope but the priority is given to local variable
a=2
def f(5);
a=10 # local variable
print(“The output is “,a)
output : the output is 10
Rule – value of global variable can be modified using global keyword
a=2
def f(5);
global a
a=a+5
return a
>>> a output is 2
>>> f(5) output is 7
>> a output is 7
Q Boards -
x=100
def myfunc(a):
k=a
print(k,a)
p=(0,1,2,3,4)
myfunc(p)
print(x)
ans :
x=100 # global variable x
def myfunc(a): # local variable a
k=a # local variable k
print(k,a)
p=(0,1,2,3,4) # global variable p
myfunc(p)
print(x)
what is output ? ( Aditya pandey question )
g=0 # g is declared outside function so g is 0
def func1(x,y): # x is 2 y is 3
global g
g=x-y value is g is -1 ( global g )
return g
def func2(m,n): # m is -1 and n is 7
global g
g=m-n change the value of g is -1 -7 =-8
return g
k=func1(2,3) # execution starts from here then value of k is -1
func2(k,7) # -1 and 7 goes to func 2
print(g) the result is -8
output is -8
What is output ( Aditya pandey)
def foo(s1,s2): s1→ “FUN” , s2→”DAY”
l1=[]
l2=[]
for x in s1: # traverse in s1
l1.append(x)
for x in s2: # traverse in s2
l2.append(x)
return l1,l2 l1=[‘F’,’U’,’N’], l2=[‘D’,’A’,’Y’]
a,b=foo("FUN","DAY") a=[‘F’,’U’,’N’], b=[‘D’,’A’,’Y’]
print(a,b)
output is [‘F’,’U’,’N’] [‘D’,’A’,’Y’]
Stack ( Compulsory)
1. Stack concept - 1. Stack is a linear data structure.
2. Value is inserted in a stack from top.
3. Stack is a Lifo structure ( Last in first out)
2. Operations on stack -
A) push - insert value to stack
B) pop - delete value from stack
C) peek - get most recent value from stack
3. Condition based upon stack -
A) overflow - if we are trying to insert a new element in a stack but stack is full. It is called overflow
Condition.
B) underflow - if we want to delete value from stack but the stack is empty . It is called underflow
Condition
4. Write a menu driven program to enter and display the stack ( insert number in a stack). Stack as a
list. Also show delete value from stack
Concept of display :- let us assume stack contains 5 integer value
S
0 1 2 3 4
15 18 2 5 9
M=5 i
Description coding
Create a stack as a list S=[] or s=list()
Create a function called remove() def remove():
If the stack is empty then print If s= = []:
underflow condition print(“ stack is underflow”)
Take variable p and using pop() else:
it removes last value from stack P=s.pop()
Print(‘The deleted value is “,p)
Create a function insert() def insert():
Create a infinite loop While True:
Input numeric value to variable val val=int(input(“Enter value”))
Input() return string type value ,
int() convert into integer value
Store the value to stack (s) s.append(val)
Hint - To store the value in a list
we are using append()
Create a function display() def display():
Find out the length of stack and m=len(s)
store to variable m i=m-1
Take variable i and store the value While (i>=0):
m-1 print(s[i])
Create a while loop i=i-1
Print the value
Decrease the value of i
# menu driven program
1. Create an infinite loop while True:
2. Print the operations print(“1. Insert value to stack “)
3. Create a variable choice for print(‘2. Display stack “)
inputting options and exit from print(“3. Exit from program “)
stack choice=int(input(“Enter choice “)
Check the value of choice . If if choice = = 1:
choice is 1 then run insert() , if Insert()
choice is 2 then run display() , if elif choice = = 2:
choice is 3 run remove and if display()
choice =4 break if choice is 4 elif choice = = 3:
then print wrong choice Remove()
elif choice = = 4:
break
else:
Print(‘ Wrong choice “)
Readline() It reads one line from the file. It stores line into string. It can read a file to eol
characters. Line=f.readline()
Ex: Write a function test() which reads entire file line by line. And check how
many lines contains “you”.
Create a function test def test():
Crate a variable ctr=0 ctr=0
Open a file for reading f=open(“story.txt”,”r”)
Store enter file line by line so line=’’
Crate a loop while line:
Read a line and store to string line line=f.readline()
Split the line into words word=line.split()
Using traversal store value to k for k in word:
Check the k contains you or not if k==’you’:
Increase ctr by 1 ctr=ctr+1
Break the loop if not line:
Break
Print the counter print(ctr)
Readlines() It can read all the lines from file which are separated by using \n.
Ex: Write a program to read enter file line by line and display the lines.
Open a file for reading f=open(‘story.txt”,”r”)
Create a string lines and lines=f.readlines()
Read the entire file
Using traversal r and for r in lines:
Display lines print(r)
Close the file f.close()
Write() It takes string as a parameter and write it to text file in a single line.
It adds \n new line character to each line. \n takes 2 bytes
Ex. F.write(“hello user”)
Writelines() Multiple string can be written at the same time is using writeline()
Method -
1. Open a file in write mode f=open(“story.txt”,”w”)
2. Create a list of values city city=[‘kanpur\n”,”Delhi\n”,”Lucknow”]
3. Using writeline to write a list f.writeline(city)
To city
4. Close the file f.close()
With statement Suppose we want to write python
Is a good
Language
1. Open a file story.txt in write mode with open(“story.txt”,”w”) as f:
2. Create a list p p=[‘python\n”,”is a good\n”,”language”]
3. Traver in a list using k (loop) for k in p:
4. Write every k to file f.write(k)
5. Close the file f.close()
Append mode Open file for writing , if exist then append data to the end of file.
For appending we are using ‘a’
Condition for append -
1) if the file exist , data is not erased.
2) If file is not existing , it will be created
3) When data is written to file. Data must be written at end if file.
Ex. f=open(‘story.txt”,”a”)
Relative path Files are organized in directories ( folder). We have a module called os . Suppose
we want to access the file we are using getcwd() ( get current working directory)
Import os
d=os.getcwd()
print(d)
Path concept 1) Relative path - It starts from current directory
2) Absolute path - It starts from root directory.
Suppose our file is stored in d drive under temp directory under local directory
d:\temp\local\story.txt . It is called absolute path . Suppose we want to show the
relative path \\story.txt