Functions Inpython
Functions Inpython
Functions in Python
Function is a block of code written to carry out a specified task. Functions provide better
modularity and a high degree of code reusing.
You can Pass Data(input) known as parameter to a function
A Function may or may not return any value(Output)
There are three types of functions in Python:
I. Built-in functions The Python interpreter has a number of functions built into it
that are always available. They are listed here in alphabetical order.
II. User-Defined Functions (UDFs): The Functions defined by User is known as User
Defined Functions. These are defined with the keyword def
III. Anonymous functions, which are also called lambda functions because they are
not declared with the standard def keyword.
Functions vs Methods : A method refers to a function which is part of
2.
a class. You access it with an instance or object of the class. A function
doesn’t have this restriction: it just refers to a standalone function. This
means that all methods are functions, but not all functions are methods.
1.1 Built-in functions
Built-in Functions
abs() divmod() input() open() staticmethod()
all() enumerate( int() ord() str()
)
any() eval() isinstance() pow() sum()
basestring() execfile() issubclass() print() super()
bin() file() iter() property() tuple()
bool() filter() len() range() type()
bytearray() float() list() raw_input() unichr()
callable() format() locals() reduce() unicode()
chr() frozenset( long() reload() vars()
)
classmethod() getattr() map() repr() xrange()
cmp() globals() max() reversed() zip()
compile() hasattr() memoryview() round() import ()
complex() hash() min() set()
delattr() help() next() setattr()
dict() hex() object() slice()
dir() id() oct() sorted()
Syntax
def functionName( list of parameters ):
"_docstring"
function_block
return [expression]
By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.
>>> MyMsg2(‘Divyaditya’)
Calling Function MyMsg2() twice with different parameter
>>> MyMsg2(‘Manasvi’)
Divyaditya is learning to define Python Function
Output
Manasvi is learning to define Python Function
Z=Add3(10,12)
print(“Result “ Z)
MyFunc()
MyFunc1()
MyFunc2() Function Call
1 : 20
2 : 10 OUTPUT
Local Function are the one that are defined and declared inside a function/block and we can use them only within that function/block
a=10;
def MyFunc1(): # Function is globally defined
a=20
print("1 :",a)
def MyFunc2():
print("2 :",a)
def SubFun1(st): # Function is Locally defined
print("Local Function with ",st)
SubFun1("Local Call") Function is called Locally
MyFunc1()
MyFunc2()
SubFun1("Global Call") Function is called Globally will give error as function scope is within the function MyFun2()
1 : 20
2 : 10
Local Function with Local Call
Traceback (most recent call last):
File "C:/Users/kv3/AppData/Local/Programs/Python/Python36-32/funct.py", line 14, in <module>
SubFun1("Global Call")
NameError: name 'SubFun1' is not defined
def inc(j):
j += 1
and then expect to increment an integer i with the call inc(i). Code like this would work in some programming languages, but it has no
effect in Python, as shown in the figure at right. First, the statement i = 99 assigns to global variable i a reference to the integer 99. Then,
the statement inc(i) passes i, an object reference, to the inc() function. That object reference is assigned to the parameter variable j. At
this point i and j are aliases. As before, the inc() function’s j += 1statement does not change the integer 99, but rather creates a new
integer 100 and assigns a reference to that integer to j. But when
the inc() function returns to its caller, its parameter variable jgoes out of scope, and the variable i still references the integer 99.
def inc(j):
j += 1
return j
def mean(a):
total = 0.0
for v in a:
total += v
return total / len(a)
We have been using arrays as arguments from the beginning of the book. For example, by convention, Python collects the strings that
you type after the program name in the python command into an arraysys.argv[] and implicitly calls your global code with that array
of strings as the argument.
Side effects with arrays
Since arrays are mutable, it is often the case that the purpose of a function that takes an array as argument is to produce a side effect
(such as changing the order of array elements). A prototypical example of such a function is one that exchanges the elements at two
given indices in a given array. We can adapt the code that we examined at the beginning of
SECTION 1.4:
This implementation stems naturally from the Python array representation. The first parameter variable in exchange() is a reference to
the array, not to all of the array’s elements: when you pass an array as an argument to a function, you are giving it the opportunity to
operate on that array (not a copy of it). A formal trace of a call on this function is shown on the facing page. This diagram is worthy
of careful study to check your understanding of Python’s function-call mechanism.
A second prototypical example of a function that takes an array argument and produces side effects is one that randomly shuffles the
elements in the array,
def shuffle(a):
n = len(a)
for i in range(n):
r = random.randrange(i, n)
exchange(a, i, r) #Python’s standard function random.shuffle() does the same task.
def randomarray(n):
a = stdarray.create1D(n)
for i in range(n):
a[i] = random.random()
return a
THE TABLE BELOW CONCLUDES OUR DISCUSSION of arrays as function arguments by highlighting some typical array-procession functions.
def mean(a):
mean of an array total = 0.0
for v in a:
total += v
def write1D(a):
write a one-dimensional array (and its length) stdio.writeln(len(a))
for v in a:
stdio.writeln(v)
def readFloat2D():
read a two-dimensional array of floats (with dimensions) m = stdio.readInt()
n = stdio.readInt()
a = stdarray.create2D(m, n, 0.0)
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was
found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was
found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was
found
rindex() Searches the string for a specified value and returns the last position of
where it was found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Note: All string methods returns new values. They do not change the original string.