Unit3 (Functions and Arrays)
Unit3 (Functions and Arrays)
3.1.FUNCTIONS:
A function is a block of organized, reusable code that is used to perform a single,
related action.
Once a function is written, it can be reused as and when required. So, functions are also
called reusable code.
Functions provide modularity for programming.
Code maintenance will become easy because of functions.
When there is an error in the software, the corresponding function can be modified without
disturbing the other functions in the software.
The use of functions in a program will reduce the length of the program.
As you already know, Python gives you many built-in functions like sqrt( ), etc. but you can
also create your own functions. These functions are called user-defined functions.
By default, parameters have a positional behavior and you need to inform them in the same order
that they were defined.
Example:
def add(a,b):
"""This function sum the numbers"""
c=a+b
print c
return
Calling Function:
A function cannot run by its own. It runs only when we call it. So, the next step is to
call function using its name. While calling the function, we should pass the necessary values to
the function in the parentheses as:
add(5,12)
Example:
def add(a,b):
"""This function sum the numbers"""
c=a+b
print c
add(5,12) # 17
3.2.Default Arguments:
We can mention some default value for the function parameters in the definition.
Let’s take the definition of grocery( ) function as:
def grocery(item, price=40.00)
Here, the first argument is „item‟ whose default value is not mentioned. But the second
argument is „price‟ and its default value is mentioned to be 40.00. at the time of calling this
function, if we do not pass „price‟ value, then the default value of 40.00 is taken. If we
mention the „price‟ value, then that mentioned value is utilized. So, a default argument is an
argument that assumes a default value if a value is not provided in the function call for that
argument.
Output:
item= sugar price= 50.75
item= oil price= 40.0
Output:
sum is 15
sum is 35
sum is 65
NOTE : You can pass one or more iterable to the map() function.
Returns :
Returns a list of the results after applying the given function to each item of a given iterable (list,
tuple etc.)
EXAMPLE:
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
print(list(result)
Output :
Filtering
The function filter(function, list) offers an elegant way to filter out all the elements of a list, for
which the function function returns True. The function filter(f,l) needs a function f as its first
argument. f returns a Boolean value, i.e. either True or False. This function will be applied to
every element of the list l. Only if f returns True will the element of the list be included in the
result list.
>>> fib = [0,1,1,2,3,5,8,13,21,34,55]
>>> result = filter(lambda x: x % 2, fib)
>>> print result
[1, 1, 3, 5, 13, 21, 55]
>>> result = filter(lambda x: x % 2 == 0, fib)
>>> print result
[0, 2, 8, 34]
Reducing a List
The function reduce(func, seq) continually applies the function func() to the sequence seq. It
returns a single value.
If seq = [ s1, s2, s3, ... , sn ], calling reduce(func, seq) works like this:
At first the first two elements of seq will be applied to func, i.e. func(s1,s2) The list on
which reduce() works looks now like this: [ func(s1, s2), s3, ... , sn ]
In the next step func will be applied on the previous result and the third element of the
list, i.e. func(func(s1, s2),s3). The list looks like this now: [ func(func(s1, s2),s3), ... , sn ]
Continue like this until just one element is left and return this element as the result of
reduce()
We illustrate this process in the following example:
>>> reduce(lambda x,y: x+y, [47,11,42,13])
113
The following diagram shows the intermediate steps of the calculation:
Examples of reduce ( )
Determining the maximum of a list of numerical values by using reduce:
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
We can return the result or output from the function using a „return‟ statement in the
function body. When a function does not return any result, we need not write the return
statement in the body of the function.
Q) Write a program to find the sum of two numbers and return the result from the
function.
def add(a,b):
"""This function sum the numbers"""
c=a+b
return c
print add(5,12) # 17
print add(1.5,6) #6.5
3.6.Modules:
A module is a file containing Python definitions and statements. The file name is the
module name with the suffix.py appended. Within a module, the module‟s name (as a string) is
available as the value of the global variable __name . For instance, use your favourite text
editor to create a file called fibo.py in the current directory with the following contents:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to na,
b = 0, 1
mypckg
|
|
---__init__.py
|
|
---mod1.py
|
|
---mod2.py
Understanding __init__.py
__init__.py helps the Python interpreter to recognise the folder as package. It also specifies the
resources to be imported from the modules. If the __init__.py is empty this means that all the
functions of the modules will be imported. We can also specify the functions from each
module to be made available.
The slice() constructor creates a slice object representing the set of indices specified by
range(start, stop, step).
Syntax:
slice(stop)
slice(start, stop, step)
Parameters: start: Starting index where the slicing of object starts. stop: Ending index where the
slicing of object stops. step: It is an optional argument that determines the increment between
each index for slicing. Return Type: Returns a sliced object containing elements in the given
range only.
Aditya polytechnic colleges, surampalem. Page 10
Python programming –(302)
Output:
# String slicing
String slicing
String ='ASTRING'
AST
# Using slice constructor
SR
s1 =slice(3)
GITA
s2 =slice(1, 5, 2)
print(String[s1])
print(String[s2])
print(String[s3])
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and
convenient way to slice a string using list slicing and Array slicing both syntax-wise and
execution-wise. A start, end, and step have the same mechanism as the slice() constructor.
Below we will see string slicing in Python with example.
Syntax
arr[start:stop] # items start through stop-1
arr[start:] # items start through the rest of the array
arr[:stop] # items from the beginning through stop-1
arr[:] # a copy of the whole array
arr[start:stop:step] # start through not past stop, by step
Example 1:
In this example, we will see slicing in python list the index start from 0 indexes and ending
with a 2 index(stops at 3-1=2 ).s
String = “welcome”
print(String[:3])
Output:
wel
immutability
In python, the string data types are immutable. Which means a string value cannot be updated.
We can verify this by trying to update a part of the string which will led us to an error.
# Can not reassign
t= "my python"
print type(t)
t[0] = "m"
When we run the above program, we get the following output −
t[0] = "M"
TypeError: 'str' object does not support item assignment
We can further verify this by checking the memory location address of the position of the letters
of the string.
:
OUTPUT:
EXAMPLE: 11
string = “Intellipaat” 27
print(len(string)) tel
string = “Intellipaat Python program” Intel
print(len(string)) taapilletni
a = “Intellipaat” [‘Intellipaat’, ‘Python’, ‘program’]
print (a[2:5]) I like Python
a = “Intellipaat”
print (a[:5])
x = “intellipaat” [::-1]
print(x)
x=”Intellipaat Python progarm”
a=x.split()
print(a)
a = ”I like Programming”
b = a.replace(“Programming”, “Python”)
print(b)
>>> string.digits
'0123456789'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
The following 3 function are equivalent to the previous 3 functions:
1. string.ascii_letters 2.string.ascii_lowercase3. string.ascii_uppercase
>>> string.expandtabs("a a\t",4)
'a a '
>>> string.whitespace
'\t\n\x0b\x0c\r '
>>> string.octdigits
'01234567'
Example:
The type code character should be written in single quotes. After that the elements
should be written in inside the square braces [ ] as
a = array ( „i‟, [4,8,-7,1,2,5,9] )
Importing the Array Module:
There are two ways to import the array module into our program.
The first way is to import the entire array module using import statement as,
import array
when we import the array module, we are able to get the „array‟ class of that module that
helps us to create an array.
a = array.array(‘i’, [4,8,-7,1,2,5,9] )
Here the first „array‟ represents the module name and the next „array‟ represents the class
name for which the object is created. We should understand that we are creating our array as
an object of array class.
3.14.accesing of an array:
Indexing and slicing of arrays:
An index represents the position number of an element in an array. For example, when
we creating following integer type array:
Aditya polytechnic colleges, surampalem. Page 15
Python programming –(302)
a = array(‘i’, [10,20,30,40,50] )
Python interpreter allocates 5 blocks of memory, each of 2 bytes size and stores the
elements 10, 20, 30, 40 and 50 in these blocks.
10 20 30 40 50
a[0] a[1] a[2] a[3] a[4]
Example:
from array import *
a=array('i', [10,20,30,40,50,60,70])
print "length is",len(a)
print " 1st position character", a[1]
print "Characters from 2 to 4", a[2:5]
print "Characters from 2 to end", a[2:]
print "Characters from start to 4", a[:5]
print "Characters from start to end", a[:]
a[3]=45
a[4]=55
print "Characters from start to end after modifications ",a[:]
Output:
length is 7
1st position character 20
Characters from 2 to 4 array('i', [30, 40, 50])
Characters from 2 to end array('i', [30, 40, 50, 60, 70])
Characters from start to 4 array('i', [10, 20, 30, 40, 50])
Characters from start to end array('i', [10, 20, 30, 40, 50, 60, 70])
Characters from start to end after modifications array('i', [10, 20, 30, 45, 55, 60, 70])
3.15.Array Methods:
Method Description
a.append(x) Adds an element x at the end of the existing array a.
a.count(x) Returns the number of occurrences of x in the array a.
a.extend(x) Appends x at the end of the array a. „x‟ can be another array or
iterable object.
a.fromfile(f,n) Reads n items from from the file object f and appends at the end of
the array a.
a.fromlist(l) Appends items from the l to the end of the array. l can be any list or
iterable object.
a.fromstring(s) Appends items from string s to end of the array a.
a.index(x) Returns the position number of the first occurrence of x in the array.
Raises „ValueError‟ if not found.
a.pop(x) Removes the item x from the array a and returns it.