Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Functions

The document discusses functions in Python. It defines what functions are and explains that they allow programmers to organize code and reuse code by defining tasks that can be called. It then covers different types of Python functions like built-in functions, functions in modules, and user-defined functions. The rest of the document discusses function parameters, arguments, returning values from functions, and various ways of passing values to functions like positional arguments, default arguments, keyword arguments, and more.

Uploaded by

puneetsarda06
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Functions

The document discusses functions in Python. It defines what functions are and explains that they allow programmers to organize code and reuse code by defining tasks that can be called. It then covers different types of Python functions like built-in functions, functions in modules, and user-defined functions. The rest of the document discusses function parameters, arguments, returning values from functions, and various ways of passing values to functions like positional arguments, default arguments, keyword arguments, and more.

Uploaded by

puneetsarda06
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

XII D – Computer Science (Python)

S. Murugan @ Prakasam
PGT Teacher, Computer Science Dept
Functions
➢ A Function is a set of statements that take inputs, do some
specific task and produces output.

➢ The idea is to put some commonly (or) repeatedly done task


together and make a function, Instead of writing the same code
again and again for different inputs.

➢ A large program is broken down into smaller units known as


functions, it used to reduce the program size.

➢ Function make a program more readable and understandable


to programmer.
Python Function Type:
➢ Build in Function: These are predefined functions and are
always available for use.
E.g. print(), int(), float(), input() etc.
print(“Welcome to India”), a=int(5.7)
➢ Functions Defined in Modules: These are predefined
functions in particular modules and can only be used when
the corresponding module is imported.
E.g. sin(),log(),sqrt(),pow()etc. # import math

➢ User Defined Function: These functions are defined by the


Programmer(User).
E.g. xyz() or hai() or add()
Parameter: its variable in the declaration of function.
Argument: it’s the actual value of this variable that gets passed to function.
a=10
def add(a,b):
b=15
print("Sum of A+B=",a+b) print("Sum of A+B=",a+b)
add(10,15) a=-10
add(-10,-15) b=-15
add(100,200) print("Sum of A+B=",a+b)
add(500,-100) a=100
b=200
Output: print("Sum of A+B=",a+b)
a=500
b=-100
print("Sum of A+B=",a+b)
Output:
def multiply(a,b): a=3
print("Output=",a*b) b=4
multiply(3,4) print("Output=",a*b)
a=9
p=9
print("Output=",a*5) #(9,5)
multiply(p,5) #(9,5)
print(“8/3 = ",8/3)
print(“8/3 = ",8/3)
print("Output=",a*(a+5)) #(9,5)
multiply(p,p+5) #(9,14)

Output:
Output:
def Calc(a,b):
def Calc(a,b): Div=a/b
Div=a/b print("Result of A/B:",Div)
print("Result of A/B:",Div) print("Main Segment\n")
print("Main Segment\n") num=12
num=12 print(num)
print(num) Calc(10,2)

Output: Output:
def Calc(a,b): def Calc(a):
Div=a/b print("Result of A:",a)
print("Result of A/B:",Div) print("Main Segment\n")
print("Main Segment\n") num=12
num=12 print(num)
print(num) Calc(10,20)
Calc(10)
Output: Output:
Function Call Statements
Syntax:
<function name>(<value to be passed to argument>)
def Calc(a):
➢ Calc(5) # here Value 5 is being sent as argument to ’a’’.
➢ num=10,
Calc(num) # here pass value as Variable num to argument ‘a’.
➢ N=int(input(“Enter a Number:”))
Calc(N) # here pass value as Variable N to argument ‘a’.
(taking input)
➢ Print(Calc(3)) #Calc(3) will get the computed result & which will
be then printed(function call inside another statement)
➢ Double=2*Calc(6) #function call’s result will be multiplied with 2
(function call inside expression)
Function Call Statements
def Calc(a): #5 #12 #7 #3#6
result=a+a #12
print(result,'\n')
return result #12
print("Main Segment\n")
Calc(5) #10
num=12
Calc(num) #24
N=int(input('Enter a Number:'))
Calc(N) #14
print(Calc(3),"\n") #6
Double=2*Calc(6) #2*12
print("\n")
print(Calc)
print(Double)
Function Call Statements
def FCall(a,b): Output
e=a+b
print("1st Time Output=",e)
return e
def FCall(a,b):
e=a*b
print("2nd Time Output=",e)
return e
a=FCall(2,3)
print(a)
b=FCall(7,10)
print(b)
c=Fcall(7,7)
def FunCall3(a,b,c):
d=a*b*c Output
print("Three Parameter Output=",d)
def FunCall2(x,y):
print("Two ParameterOutput=",x*y)
def FunCall2R(x,y):
z=x*y
print("Two ParameterOutput=",z)
return z
def FunCall2a(a,b):
e=a+b
print("2 Parameter Output=",e)
return e
def FunCall(q):
print("Single Parameter Output=",q)
FunCall3(3,4,5)
print("Returned Result is:",FunCall2(2,3))
print("Returned Result of FC2R is:",FunCall2R(3,5))
RDiv=100*FunCall2a(2,3)
print(RDiv)
FunCall(1,2,3,4)
Parameter Passing
Python Provides some other ways of “Sending and Matching”
arguments and parameters.
Positional Parameter Passing/Calling:
Here we need Match the No. of Arguments and No. of Parameters
required & Order required.

def position(name,age,city):
print("Name:",name,"Age:",age,"City:",city)
position("Rahul",18,"Chennai")
position("Ramesh",19,"Kovai")
position(17,"Madurai","Saravanan")

Output:
Default Arguments:
A parameter having default value in function header become
optional in function call, function call may (or) may not have value for it.

def defaultarg(name,city="Chennai",age=18): Output:


print("Person Name:",name)
print("Person City:",city)
print("Person Age:",age)
defaultarg("Mathan")
defaultarg('VK','Bangalore')
x,y,z='MDS','Chennai’,37
defaultarg(x,y,z)
defaultarg('YV')
Keyword Arguments:
Keyword arguments are the named arguments with assigned
values being passed in the function call statement, No order required.

def keyword(rno,name,studyclass): Output:


print("Student R.No.:",rno)
print("Student Name:",name)
print("Student StudyingClass:",studyclass)
keyword(17,'Rahul','XII')
keyword(studyclass="XI",rno=12,name="yv")
keyword(name='MDS',studyclass='XII',rno=37)
Variable Length Arguments:
This arguments use the symbol * to take in a variable ‘N” Number of
Arguments.

def adder(*N): #N=[3,5] Output:


sum=0
for n in N: #3
sum=sum+n #0+3 sum=3+5
print("Sum=",sum)
adder(3,5)
adder(3,5,7,9)

def adder(num,*num2):
sum=0
for n in num2: #[5,7,9]
sum=sum+n
print("Sum2=",sum)
print("NUM:",num)
adder(3,5,7,9)
Passing Strings, Lists, Tuples and Dictionaries to Functions
Strings, Lists to Functions:
def strings(n1,n2,n3): Output:
print("Student Name1:",n1)
print("Student Name2:",n2)
print("Student Name3:",n3)
strings('MSD','Rahul','VK')

def list(l1,l2,l3):
print("List[1] Value:",l1)
print("List[2] Value:",l2)
print("List[3] Value:",l3)
lst=['MSD',37,50.50]
list(*lst) # list('MSD',37,50.50)

def list2(ff):
for i in ff:
print("List Value:",i)
lufl=['VK',31,55.55]
list2(lufl)
Tuple to Functions
def tuple(t1,t2,t3): Output:
print("Tuple[1] Value:",t1)
print("Tuple[2] Value:",t2)
print("Tuple[3] Value:",t3)
tup=('MSD',37,50.50)
tuple(*tup) #tuple('MSD',37,50.50)

def tuple2(tt): #('VK',31,55.55)


for i in tt:
print("Tuple Value : ",i)
tufl=('VK',31,55.55)
tuple2(tufl)

def tuple3(*tt): #(‘yv’,37,45.45)


for i in tt:
print("Tuple Value : ",i)
tuple3('YV',37,45.45)
Dictionary to Functions
def Dictionary1(df):
for i in df: # i=(Name:VK)
print("Dic Key:",i,",Dic Value:",df[i])
Dic1={'Name':'VK','Age':31,'Average':56.56}
Dictionary1(Dic1)

def Dictionary2(dn):
for i in dn:
print("Dic Key:",i,",Dic Value:",dn[i]*2)
Dic2={'Name':'Mersey','Age':35,'Goals':1000}
Dictionary2(Dic2)

def Dictionary(name,age,average):
print("Dictionary[1] Value:",name)
print("Dictionary[2] Value:",age)
print("Dictionary[3] Value:",average)
Dic={"Name":'MSD',"Age":37,"Average":50.50}
Dictionary(**Dic)
Simple Interest Calculation using Function
def interest(Principal, Time=2, Irate=0.10):
return Principal*Time*Irate #4000
Principal=float(input("Enter the Principal Amount:")) #20000
print("Simple Interest with Default time and Interest Rate")
si1=interest(Principal) #4000
print("Rs:",si1)
roi=float(input("Enter Rate of Interest(Real No):"))
time=int(input("Enter the Time in Years:"))
print("Simple Interest with out Default time and Interest Rate")
si2=interest(Principal, time, roi/100)
print("Rs:",si2)
Returning Values from Functions
Functions Returning Some Value(Non-Void Function):
➢Return Statement that return the computed value
Syntax: return<value>
Some legal return statement:
➢ return 5 # literal being returned.
➢ return a # variable being returned.
➢ return a**5 # expression involving V&L to
returned.
➢ return a+b/c # expression involving Variables
to returned.
➢ return (a+8*b)/c # expression involving V&L to
returned.
(Non-Void Function with Arguments & without Arguments):
def sum(x,y):
s=x+y #18 Output:
return s
def noarg():
print("No Arguments Passed")
return 10
def express(a,b):
print("Arguments Passed:",a,"and",b)
return 10*a+b #10*9+8

result=sum(10,8)
print("Result :",result)
rn=noarg() #10
print("Without Any Arguments:",rn)
x,y=9,8
rn=express(x,y)
print("Expression:",rn)
Void Function with Arguments & without Arguments:
def multi(a,b,c):
d= a*b*c
print("Mult=",d) Output:
return
m=multi(6,7,8)
print(m)
print("\n")

def great():
print("Hello World")
a=great()
print(a)
Scope of Variable:
➢ Scope refers to parts of program within which a name is legal and accessible.
➢ Scope refers to the visibility of variables.
➢ Its follow the LEGB.
Default every variable has a global scope, every part of your program can
access a variable.
➢ Global Scope: a global variable is a variable defined in the main program.
➢ Local Scope: a local variable is a variable defined with in a function.

Name Resolution
Local Scope:
def printnum():
a=5
print("The 'A' Assigned with Value:", a) Output:
printnum()
print("A:", a)
print("\n")
Enclosing Scope:
def loop1():
firstno=7
def loop2():
secondno=3
print("First No:",firstno)
print("Second No:",secondno)
loop2()
loop1() #main statement
print("\n")
Global Scope:
def greetworld():
a='world'
print(greeting,a) Output:
def greetname(name):
print(greeting,name)
greeting="Hello"
greetworld()
greetname("google")

Built in Scope:
from math import pi
def built():
i=10 #pi=3.14
print("No Data")
def innerloop():
#pi=3.14
print(pi)
innerloop()
p=10 #pi=3.14
built()
Same variable name in local and global scope, use global
available inside local scope
def state():
tigers=15 Output:
print("Local:",tigers)
tigers=95
print(tigers)
state()
print("No Return :",tigers)
print("\n")

def state():
global tigers
print("Global:",tigers)
tigers=15
print("Local:",tigers)
tigers=95
print(tigers)
state()
print("No Return :",tigers)
Immutable Function Argument:
def immfun(a): a=15
print("A=",a)
print("ID of A:",id(a)) a=15 Output:
a+=10 #a=a+10 #a=25
print("After the Change of A=",a)
print(“iD of A After Change:",id(a))
return a #a=25
x=15
y=immfun(x) #a
print("x=",x)
print("y=",y)
print("ID of X:",id(x))
print("ID of Y:",id(y))
Mutable Function Argument
def mut1(funclist): #[10,20,25,30] Output:
funclist.append(30)
funclist.extend([18,27,36])
def mut2(funclist):
del funclist[1]
def mut3(funclist):
funclist[0]=12
a=[10,20,25]
print("Original List:",a)
print("List1 ID:",id(a))
mut1(a)
print("\n List after updation in mut1():",a)
print("List2 ID after Mut1():",id(a))
mut2(a)
print("\n List1 after updation in mut2():",a)
print("List1 ID after mut2():",id(a))
mut3(a)
print("\n List1 after updation in mut3():",a)
print("List ID after mut3():",id(a))
Mathematical Function
import math as m
def mathfun(): Output:
a, b, c, d, e, f = -10.7, 12.7, 2, 16, 90, 12.3
print("The Ceil Value of A:",m.ceil(a))
print("The Ceil Value of B:",m.ceil(b))
print("The Ceil Value of F:",m.ceil(f))
print("The Floor Value of A:",m.floor(a))
print("The Floor Value of B:",m.floor(b))
print("The Floor Value of F:",m.floor(f))
print("The Fabs Value of A:",m.fabs(a))
print("The Exp Value of C:",m.exp(c))
print("The SQRT Value of D:",m.sqrt(d))
print("The Log10 Value of C:",m.log10(c))
print("The D to the Power C Value:",m.pow(d,c))
print("The Sin Value of C:",m.sin(c))
print("The Cos Value of C:",m.cos(c))
print("The Tan Value of C:",m.tan(c))
print("The Degrees Value of C:",m.degrees(c))
print("The Radian Value of C:",m.radians(c))
mathfun() # 1Deg × π/180 = 0.01745Rad
print("These are all the some Mathematical Functions") #e=2.7182 # 1Rad × 180/π = 57.296Deg
String Function
def string(func):
sg=func
print("Value Pssed is:",sg)
Capital=sg.capitalize()
print("Capitalize:",Capital)
print("The Length of a String is:",len(sg))
print("Each Title is Capitalized:", sg.title())
str="python is awesome, it is a good language"
print("Partition :",str.partition('awesome'))
song='cold,cold heart'
song2='let it be,let it be‘,’
print("Replace:", song.replace('cold','hurt'))
print("Replace no.of words:",song2.replace('let',"'don't let",1))
sub="operator"
print("Find:",sg.find(sub))
sub2="is"
print("start and end point find:",sg.find(sub2,1,20))
print("Count String:",str.count(sub2))
print("Main Function Block")
string('the + is an operator')
print("End of String Functions")
def string():
mylist=[7,8,5,6,2,4] Output:
print("Find the Index:",mylist.index(4))
splitv=" hi,hello,india "
strp=" Hi! "
print("Split:",splitv.split(','))
print("Strip:",strp.strip())
print("lStrip=",strp.lstrip())
print("rStrip=",strp.rstrip())
sub="operator"
sub3='12345'
sub4, sub5 = '23ghij', "HAI"
print("All Characters are Numeric:",sub4.isalnum())
print("All Characters are Alphabets:",sub.isalpha())
print("All Characters are Digit:",sub3.isdigit())
print("Find only WhiteSpace:",sub4.isspace())
print("All Char are in Lowercase:",sub.islower()),
print("All Char are in Uppercase:",sub5.isupper())
print("Convert all to Lower:",sub5.lower()), print("Convert all to Upper:",sub4.upper())
print("Main Function Block")
string()
print("End of String Functions")
def string():
mld,idr='python','12thpython‘ Output:
print("Valid Identifier;",mld.isidentifier())
print("Valid Identifier 2:",idr.isidentifier())
pp,tt="Hello world","\n hello"
print("printable:",pp.isprintable())
print("2nd printable:",tt.isprintable())
print("Title Case:",pp.istitle())
print("Swapcase:",tt.swapcase())
print("Center String:",idr.center(10))
print("CenterStringandFill:",idr.center(16,'*'))
pylist=['h','z','x','e','a']
pystring='python'
pytuple=('p','y','n')
print("Sorted list:",sorted(pylist))
print("Sorted String:",sorted(pystring))
print("Sorted Tuple:",sorted(pytuple))
print("Reverse:",reversed(mld))
print("Main Function Block")
string()
print("End of String Functions")
Thank You

You might also like