0% found this document useful (0 votes)
2 views9 pages

Python 4

The document provides an overview of Python functions, including defining functions, using return statements, passing arguments, and handling default and variable-length arguments. It includes examples demonstrating function calls, keyword arguments, and error handling when incorrect arguments are provided. Additionally, it covers the use of return values in functions and showcases various function definitions and their outputs.

Uploaded by

mpari0181
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

Python 4

The document provides an overview of Python functions, including defining functions, using return statements, passing arguments, and handling default and variable-length arguments. It includes examples demonstrating function calls, keyword arguments, and error handling when incorrect arguments are provided. Additionally, it covers the use of return values in functions and showcases various function definitions and their outputs.

Uploaded by

mpari0181
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

defhf():

print("hw")

print("ghkfjg66666")

hf()

hf()

hf()

Output:

hw
ghkfjg66666
hw
ghkfjg66666
hw
ghkfjg66666

defadd(x,y):

c=x+y

print(c)

add(5,4)

Output:

defadd(x,y):

c=x+y

return c

print(add(5,4))

Output:

9
defadd_sub(x,y):

c=x+y

d=x-y

returnc,d

print(add_sub(10,5))

Output:

(15,5)

Thereturnstatement is used to exit a function and go back to the place from where it was
called. Thisstatementcancontain expressionwhichgetsevaluatedandthevalueisreturned. If
there is no expression in the statement or the returnstatement itself is not present inside a
function, then the function will return the None object.

defhf():

return"hw"pri

nt(hf()) Output:

hw

defhf():

return"hw"hf(

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]

>>>
defhello_f():

return"hellocollege"print

(hello_f().upper()) Output:

HELLOCOLLEGE

#PassingArguments

defhello(wish):

return'{}'.format(wish)

print(hello("mrcet"))

Output:

mrcet

Here, the function wish()has two parameters. Since, we have called this function with two
arguments, it runs smoothly and we do not get any error. If we call it with different number
of arguments, the interpreter will give errors.

def wish(name,msg):

"""Thisfunctiongreetsto

thepersonwiththeprovidedmessage"""

print("Hello",name +' ' + msg)

wish("MRCET","Goodmorning!")

Output:

HelloMRCETGoodmorning!
Below is a call to this function with one and no arguments along with their respective error
messages.

>>>wish("MRCET") #onlyoneargument
TypeError:wish()missing1requiredpositionalargument:'msg'
>>> wish() #noarguments
TypeError:wish()missing2requiredpositionalarguments:'name'and'msg'

defhello(wish,hello):

return“hi”'{},{}'.format(wish,hello)

print(hello("mrcet","college"))

Output:

himrcet,college

#KeywordArguments

Whenwecallafunctionwithsomevalues,thesevaluesgetassignedtothearguments according to their


position.

Python allows functions to be called using keywordarguments. When we call functions


inthis way, the order (position) of the arguments can be changed.

(Or)

If you have some functions with many parameters and you want to specify only some
ofthem,thenyoucangivevaluesforsuchparametersbynamingthem-thisis called keyword
arguments - we use the name (keyword) instead of the position (which we have been
using all along) to specify the arguments to the function.

There are two advantages- one, using the function is easier since we do not need to
worry about the order of the arguments. Two, we can give values to only those
parameters which we want, provided that the other parameters have default argument
values.

deffunc(a,b=5,c=10):
print 'ais',a,'andbis',b,'and cis',c
func(3, 7)func(25,
c=24)
func(c=50,a=100)

Output:

a is 3 and b is 7 and c is 10
ais25andbis5andcis24
ais 100 andb is 5 and cis 50

Note:

The function named func has one parameter without default argument values,
followed by two parameters with default argument values.

In the first usage, func(3, 7), the parameter agets the value 3, the parameter bgets the value
5 and c gets the default value of 10.

In the second usagefunc(25, c=24), the variable agets the value of 25 due to the
position of the argument. Then, the parameter cgets the value of 24due to naming i.e.
keyword arguments. The variable b gets the default value of 5.

In the third usage func(c=50, a=100), we use keyword arguments completely to


[Link],thatwearespecifyingvalueforparameter cbeforethat for a even
though a is defined before c in the function definition.

Forexample:ifyoudefinethefunctionlikebelow

deffunc(b=5,c=10,a):#showserror:non-defaultargumentfollowsdefaultargument

defprint_name(name1,name2):

"""Thisfunctionprintsthename"""

print(name1+"and"+name2+"arefriends") #calling

the function

print_name(name2='A',name1='B')
Output:

Band Aare friends

#DefaultArguments

FunctionargumentscanhavedefaultvaluesinPython.

Wecanprovideadefaultvaluetoanargumentbyusingtheassignmentoperator(=) def

hello(wish,name='you'):

return'{},{}'.format(wish,name)

print(hello("good morning"))

Output:

goodmorning,you

defhello(wish,name='you'):

return '{},{}'.format(wish,name) //print(wish+‘‘ +name)

print(hello("good morning","nirosha")) //hello("goodmorning","nirosha")

Output:

goodmorning,nirosha // goodmorningnirosha

Note: Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.

Thismeanstosay,[Link],if we had
defined the function header above as:

defhello(name='you',wish):

SyntaxError:non-defaultargumentfollowsdefaultargument

defsum(a=4,b=2):#2issuppliedasdefault argument
"""Thisfunctionwillprintsumoftwonumbers if

the arguments are not supplied

itwilladdthedefaultvalue""" print

(a+b)

sum(1,2)#calling with arguments

sum( ) #callingwithoutarguments

Output:

Variable-lengtharguments

Sometimes you may need more arguments to process function then you mentioned in the
definition. If we don’t know in advance about the arguments needed in function, we can use
variable-length arguments also called arbitrary arguments.

For this an asterisk (*) is placed before a parameter in function definition which can hold
non-keyworded variable-length arguments and a double asterisk (**) is placed before a
parameter in function which can hold keyworded variable-length arguments.

If we use one asterisk (*) like *var,then all the positional arguments from that point till the
endarecollectedasatuplecalled‘var’andifweusetwo asterisks(**)beforeavariablelike
**var,thenallthepositionalargumentsfromthatpointtilltheendarecollectedas a dictionary called
‘var’.

def wish(*names):
"""Thisfunctiongreetsall
thepersoninthenames tuple."""

#namesisatuplewitharguments for
name in names:
print("Hello",name)

wish("MRCET","CSE","SIR","MADAM")
Output:

Hello MRCET
Hello CSE
Hello
SIRHelloMAD
AM

#Programtofindareaofacircleusingfunctionusesinglereturnvaluefunctionwith argument.

pi=3.14
def areaOfCircle(r):

returnpi*r*r
r=int(input("Enterradiusofcircle"))

print(areaOfCircle(r))

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Enter radius of circle 3
28.259999999999998

#Program to write sum different product and usingargumentswithreturnvalue


function.

defcalculete(a,b):

total=a+b

diff=a-b

prod=a*b

div=a/b mod=a

%b

You might also like