Module III
Array,String & Functions
Functions – Defining Functions, Calling Functions, Passing Arguments, Keyword
Arguments, Default Arguments, Variable-length arguments, Anonymous Functions,
Fruitful Functions (Function Returning Values), Scope of the Variables in a
Function- Global and Local Built-In Functions Used on Tuples, Default Parameters,
Command Line Arguments.
Arrays:
An array is an object that stores a group of elements of the same data type. It means
we can store only integer type elements or only float type elements into an array. But we
cannot store one integer, one float and one character type element into the same array.
Arrays can increase or decrease their size dynamically. It means, we need not declare
the size of the array. When the elements are added, it will increase its size and when the
elements are removed, it will automatically decrease its size in memory.
Creating an array:
Syntax 1:
From array import *
arrayname = array(type code, [elements])
Syntax 2 :
import array
Arrayname=[Link](type code,[elements])
OR:
import array as arr
Arrayname=[Link](type code,[elements])
The type code „i‟ represents integer type array where we can store integer numbers. If the
type code is „f‟ then it represents float type array where we can store numbers with
decimal point.
Type code Description Minimum size in bytes
„b‟ ----------------- Signed character -------- 1
„B‟ ----------------- Unsigned character ------ 1
„i‟ ------------------ Signed integer -------- 2
„I‟ ----------------- Unsigned integer ----- 2
„l‟ ------------------ Signed long integer -------- 4
„L‟ ----------------- Unsigned long integer ----- 4
„f‟ ----------------- Floating point -------- 4
„d‟ ----------------- Double precision floating point -> 8
„u‟ ---------------- Unicode character ------- 2
“h” -----------------signed short int -------- 2
“H” ---------------unsigned shortint --------- 2
Example :
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
Output:
10
20
30
40
50
Example :
import array
array1 = [Link]('i', [10,20,30,40,50])
for x in array1:
print(x)
Output:
10
20
30
40
50
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:
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) #length is 7
print " 1st position character", a[1] # 1st position character 20
print "Characters from 2 to 4", a[2:5] #characters from 2 to 4 [30,40,50]
print "Characters from 2 to end", a[2:] #characters from2 to end [30,40,50,60,70]
print "Characters from start to 4",a[:5] #characters from start to4 ,[10,20,30,40,50]
print "Characters from start to end",a[:] #characters from start to end
[10,20,30,40,50,60,70]
a[3]=45
a[4]=55
print "Characters from start to end after modifications ",a[:] #characters from start to end
after modification [10,20,30,45,55,60,70]
Array Methods:
1) [Link](x): Adds an element x at the end of the existing array a.
from array import *
array1 = array('i', [10,20,30,40,50])
[Link](60)
for x in array1:
print(x)
2) [Link](x): Returns the number of occurrences of x in the array a.
from array import *
array1 = array('i', [10,20,30,40,50,60])
[Link](60)
for x in array1:
print(x)
c=[Link](60)
print(c)
3) [Link](x): Appends x at the end of the array a. „x‟ can be another array or
iterable object.
from array import *
array1 = array('i', [10,20,30,40,50,60])
[Link]([70,80,90])
for x in array1:
print(x)
4) [Link](x): Returns the position number of the first occurrence of x in the array.
from array import *
array1 = array('i', [10,20,30,40,50,60])
print([Link](20))
5) [Link](x): Removes the item x from the array a and returns it.
from array import *
array1 = array('i', [10,20,30,40,50,60])
print([Link](2))
print(array1)
6) [Link]( ): Removes last item from the array a
from array import *
array1 = array('i', [10,20,30,40,50,60])
print([Link]())
7) [Link](x) : Removes the first occurrence of x in the array.
from array import *
array1 = array('i', [10,20,30,40,50,60])
print([Link](4))
8) [Link]( ) : Reverses the order of elements in the array a.
from array import *
array1 = array('i', [10,20,30,40,50,20,60])
print([Link](20))
print(array1)
9) [Link]( ): Converts array „a‟ into a list.
from array import *
array1 = array('i', [10,20,30,40,50,20,60])
print([Link]())
print(array1)
Strings
A string is a group/ a sequence of characters. We can use a pair of single or double quotes.
Every string object is of the type ‘str’.
Ex: X=” Hello”
Print(type(X)
O/P: <class 'str'>
Ex: S=’Python’
Print(S[2])
O/P: t
String slices:
A segment of a string is called a slice. Subsets of strings can be taken using the slice
operator ([ ] and [:]) with indexes starting at 0 in the beginning of the string and working
their way from -1 at the end.
Syntax: [Start: stop: steps]
Default value of start is 0, Stop is last index of list, And for step default is 1
Ex: str = 'Hello World!'
print str # Prints complete string ->Hello World!
print str[0] # Prints first character of the string -> H
print str[2:5] # Prints characters starting from 3rd to 5th -> llo
print str[2:] # Prints string starting from 3rd character print -> llo World!
str * 2 # Prints string two times -> Hello World ! Hello World!
print str + "TEST" # Prints concatenated string -> Hello World!TEST
Ex:
x='computer'
Print(x[1:4]) -> 'omp'
Print(x[1:6:2]) -> 'opt'
Print(x[3:]) -> 'puter'
Print(x[:5]) -> 'compu'
Print(x[-1]) -> 'r'
Print(x[-3:]) -> 'ter'
Print(x[:-2]) -> 'comput'
Print(x[::-2]) -> 'rtpo'
Print(x[::-1]) -> 'retupmoc'
String functions and methods:
1. isalnum(): Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
Ex: string="123alpha"
print([Link]()) -> True
2. isalpha(): Returns true if string has at least 1 character and all characters are alphabetic
and false otherwise.
Ex: string="nikhil"
print([Link]()) -> True
3. isdigit(): Returns true if string contains only digits and false otherwise.
Ex: string="123456789"
print([Link]()) ->True
4. islower(): Returns true if string has at least 1 cased character and all cased characters
are in lowercase and false otherwise.
Ex: string="nikhil"
print([Link]()) ->True
5. isnumeric(): Returns true if a string contains only numeric characters and false
otherwise.
Ex: string="123456789"
print([Link]()) ->True
6. isspace(): Returns true if string contains only whitespace characters and false
otherwise.
Ex: string=" "
print([Link]()) -> True
7. istitle(): Returns true if string is properly “titlecased” and false otherwise.
Ex: string="Nikhil Is Learning"
print([Link]()) -> True
8. isupper(): Returns true if string has at least one cased character and all cased characters
are in uppercase and false otherwise.
Ex: string="HELLO"
Print([Link]()) -> True
9. replace(old, new [, max]): Replaces all occurrences of old in string with new or at most
max occurrences if max given.
Ex: string="Nikhil Is Learning"
[Link]('Nikhil','Neha')
print(string) -> Neha is learning
[Link](): Splits string according to delimiter str (space if not provided) and returns list of
substrings;
Ex: string="Nikhil Is Learning"
print([Link]()) ->[‘Nikhil’,’Is’,’Learning’]
[Link](): Occurrence of a string in another string
Ex: string='Nikhil is Learning'
print([Link]('i')) -> 4
[Link](): Finding the index of the first occurrence of a string in another string.
Ex: string="Nikhil Is Learning"
print([Link]('k')) ->2
[Link](): Converts lowercase letters in a string to uppercase and vice versa.
Ex: string="helo"
print([Link]()) -> HELO
[Link](str,beg=0,end=len(string)): Determines if string or a substring of string (if
starting index beg and ending index end are given) starts with substring str; returns true
if so and false otherwise.
Ex: string="Nikhil Is Learning"
print([Link]('k')) -> False
15. endswith() : Determines if string or a substring of string (if starting index beg and
ending index end are given) ends with substring str; returns true if so and false
otherwise.
Ex: string="Nikhil Is Learning"
print([Link]('g')) -> True
Functions & Methods
A Function is a block of program statements that performs a single, specific, and well-
defined task. Python enables its programmers to break the program into functions, each of
which has a specific task.
When a function is called, the program control is passed to the
function definition. All the statements in the function are executed in sequence and the
control is transferred back to the function call. The function that calls another function is
known as the “Calling Function”, and the function that is being called by another function
is known as the “Called Function”
Need Functions:
Simpler Code
Code Reuse
Better Testing
Faster Development
Types of Functions:
There are two different types of functions:
1. built-in functions
2. user-defined functions.
[Link] functions such as input(), print(), min(), max() are example for the built-in
functions.
2. The user-defined functions are created by user. The user selects his own name for the
function name.
The naming rules for the function name are the same as the identifier rule.
Syntax Functions:
• The first line is known as the function header.
• It marks the beginning of the function definition.
• The function header begins with the key word def, followed by the name of the
function, followed by a set of parentheses, followed by a colon (:).
• The function body contains one or more statement.
• These statements are executed in sequence to perform the task for which it is
intended to define.
Example:
# function definition
def eventest(x):
if x%2==0:
print(“even”)
else
print(“odd”)
Calling Functions :
A function definition specifies what a function does, but it does not cause the function to
execute. To execute a function, you must call it. This is how we would call the “eventest”
function: eventest(n)
When a function is called, the interpreter jumps to that function definition and executes the
statements in its body. Then, when the end of the body is reached, the interpreter jumps
back to the part of the program that is called the function, and the program resumes
execution at that point. When this happens, we say that the function returns.
Passing Arguments to Function :
An argument is any piece of data that is passed into a function when the function is called.
This argument is copied to the argument in the function definition. The arguments that are
in the function call are known as “Actual Arguments or Parameters”. The arguments that
are in function definition are called “Formal arguments or Parameters”. We can pass one
or more number of actual arguments in the function call. The formal argument list and
their type must match with actual arguments.
Types of arguments/parameters:
I. Positional parameter
II. Default Parameter
III. Keyword Parameter
IV. Variable length Parameter
I Positional Parameter: The position of the value passed in actual argument follows the
same position as formal argument.
Example : Calculate Simple interest and find out total amount.
# finding simple interest
def si(p,t,r):
s=(p*t*r)/100
print(“The simple intresst is:”,s)
print(“Total amount:”, p+s)
print(si(5000,3,2.5))
II Default Parameter: When values are assigned through assignment operator(=) in
function definition.
Syntax:
Example:
# find the sum of three numbers
def sum(a=10,b=20,c=30):
s=a+b+c
print(“The sum is:”, s)
sum() # 60
sum(5) #55
sum(5,15) #50
sum(5,15,25) #45
III Keyword Arguments: When we call the function with the name of the actual
parameter and their assigned values.
Syntax:
Function_name(argument_name1=value1,argument_name2=value2)
Example :
# Find simple interest
def si(p,t,r):
s=(p*t*r)/100
print(“The simple intresst is:”,s)
print(“Total amount:”, p+s)
print(si(r=3,p=1000,t=3.5))
IV Variable-length Parameter: In some situations, it is not known in advance how many
number of arguments have to be passed to the function. In such cases, Python allows
programmers to make function calls with an arbitrary (or any) number of arguments.
When we use arbitrary arguments or variable-length arguments, then the function
definition uses an asterisk ( * ) before the formal parameter name.
Syntax:
def fun_name([arg1,arg2,..argn],*var_length_tuple)
Example:
def display(*args):
Print(“ Hobbies are:”)
for x in args:
print(x)
display(“Reading”, “Travelling”, “Gardening”)
display(“coding”,”gaming”)
Anonymous Functions:
• Lambda or anonymous functions are so called because they are not declared as
other functions using the def keyword. Rather, they are declared using the
lambda keyword.
• Lambda functions are throw-away functions, because they are just used where
they have been created.
• Lambda functions contain only a single line. Its syntax will be as follows:
1) Disp=lambda:print(“Hello World”)
Disp()
2) Lamda function with a single argument
x = lambda a : a + 10
print(x(5))
3) Lamda function with multiple arguments
i) x = lambda a, b : a * b
print(x(5, 6))
ii) n=lambda x,y:x**y
x=int(input(“Enter the number x:”))
y=int(input(“Enter the value for y:”))
print(x,”power”,y,”is”,n(x,y)
4) Lamda function with multiple task
calc = lambda x, y: (x + y, x * y)
res = calc(3, 4)
print(res) # output: 7 ,12
5) Lamda function with if else
check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(4))
print(check(7))
6) Lamda function within another function:
def myfunc(n):
return lambda a : a * n
pro = myfunc(2)
print(pro(11))
Properties of Lambda Functions :
lambda function can have any number of arguments but only one expression,
which is evaluated and returned.
One is free to use lambda functions wherever function objects are required.
lambda functions are syntactically restricted to a single expression.
Lambda functions cannot access variables other than in their parameter list.
Lambda functions cannot access global variables.
Difference between Lamda function and normal function
# Using lambda
sq = lambda x: x ** 2
print(sq(3))
# Using def
def sqdef(x):
a= return x ** 2
print(sqdef(3))
1) lambda with filter()
The filter() function returns an iterator where the items are filtered through a function
to test if the item is accepted or not.
Syntax:
filter(function, iterable)
n = [1, 2, 3, 4, 5, 6]
even = filter(lambda x: x % 2 == 0, n)
print(list(even)) # [2,4,6]
2) lambda with map()
The map() function is used to apply a given function to every item of an iterable, such
as a list or tuple, and returns a map object (which is an iterator).
Syntax:
map(function, iterable)
a = [1, 2, 3, 4]
b = map(lambda x: x ** 2, a)
print(list(b)) # [1,4,9,16]
3) lambda with reduce()
This function is used to apply a particular function passed in its argument to all of the
list elements mentioned in the sequence passed along.
Syntax:
reduce(function, iterable[, initializer]
function: The function to apply to the elements of the iterable. It must take two
arguments.
iterable: The iterable whose elements you want to reduce. It can be a list,
tuple, or any other iterable.
initializer (optional): The starting value. It is used as the first argument in the
first function call if provided.
Import functools
a = [1, 2, 3, 4, 5]
res = [Link](lambda x, y: x + y, a)
print(res) # 15
4) lambda with sorted()
Sorting rows in a dataset by a column by using the sorted() function.
a = [(2, 'B'), (1, 'A'), (3, 'C')]
b = sorted(a, key=lambda x: x[0])
print(b) # [(1, 'A'), (2, 'B'), (3, 'C')]
Fruitful Functions (Function Returning Values) :
The functions that return a value are called “Fruitful Functions”. Every function after
performing its task returns the program control to the caller. This can be done
implicitly. This implicit return returns nothing to the caller, except the program
control. A function can return a value to the caller explicitly using the “return”
statement
Syntax:
return (expression)
The expression is written in parenthesis that computes a single value. This return statement
is used for two things: First, it returns a value to the caller. Second, to end and exit a
function and go back to the caller.
Example:
def add():
a=15
b=24
c=a+b
return c
c=add()
print(c) #39
Scope of the Variables in a Function:
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable. The part of the program in which a
variable can be accessed is called its scope. The duration for which a variable exists is
called its “Lifetime”. If a variable is declared and defined inside a function its scope is
limited to that function only. It cannot be accessed outside that function. If an attempt is
made to access it outside that function an error is raised.
The scope of a variable determines the portion of the program where you can access
a particular identifier. There are two basic scopes of variables in Python:
• Global Scope -variables defined outside the function and part of
main program.
• Local Scope - variables defined inside functions have local scope.
Example :
def greet():
message = 'Hello' #local variable
print('Local', message) # Local Hello
greet()
print(message) # error
Example :
message = 'Hello' # global variable
def greet():
print('Local', message) # Local Hello
greet()
print('Global', message) # Global Hello
----------------------------------------------------------------------------------------------------------
Modules: Creating modules, import statement, from. Import statement,
namespacing, Python packages: Introduction to PIP, Installing Packages
via PIP, Using Python Packages
A module is a file that contains Python code. This code contains functions, classes
and variables that perform related tasks. In other words, we can say that our Python code
file saved with the extension (.py) is treated as the module. This approach is called
“Modularization”. This makes the program easier to understand, test, and maintain.
Modules also make it much easier to reuse the same code in more than one program.
If we have written a set of functions that are needed in several different programs, we can
place them in modules. Then we can import these modules in each program to call one of
the functions
Creating Modules :
Let us use functions such as area of a circle, circumference of circle, area of rectangle, and
circumference of rectangle . So we can create two modules, such as circle and rectangle,
and put the functions related to the circle in that module and the functions related to the
Rectangle in another module called rectangle. We can just import these modules into any
number of programs if their functions are needed.
Rules for naming Modules:
A module file name should end with( .py) . If it is not ended with (.py) we
cannot import it into other programs.
A module name cannot be keyword.
The module must be saved within the same folder (directory) where you are
accessing it.
Accessing Python modules:
Python modules can be accessed in two ways,
1. Using import statement
2. Using from . import statement
import statement:
To use these modules in program, we import them in program with import
statement. To import the circle module, we write it as follows:
import circle
When the Python interpreter reads this statement it will look for the file [Link] in the
same folder as the program that is trying to import it. If it finds the file it will load it into
memory. If it does not find the file, an error occurs.
Example:
[Link] Access [Link] in another program
def area(r): Import circle
a=3.141*r*r X=float(input(“enter radius of a circle”))
return a Res=[Link](x)
def circum(r): Print(“ Area of the circle:”,res)
c=2*3.141*r Res=[Link](x)
return c Print(“Circumference of circle:”,res)
We can import multiple modules with a single import statement, but a module is loaded
once, regardless of the number of times it has been imported into our file.
Syntax:
Import module1,module2, module3,…..,module n
From. Import statement:
Instead of importing the whole module into the namespace, python provides the flexibility
to import only the specific attributes of a module. This can be done by using from. import
statement.
Syntax:
from < module-name> import <name1>,<name2>,<name3> ..<name n)
[Link] [Link]
def summation(a,b): from calculation import summation
return a+b a = int(input("Enter the first number"))
def multiplication(a,b): b = int(input("Enter the second number"))
return a*b; print("Sum = ",summation(a,b))
def divide(a,b):
return a/b;
from calculation import summation, multiplication
a = int(input("Enter the first number"))
b= int(input("Enter the second number"))
print("Sum = ",summation(a,b))
print(“Product =”,multiplication(a,b))
Note:
The from...import statement is always better to use if we know the attributes to be
imported from the module in advance. It doesn't let our code to be heavier. We can also
import all the attributes from a module by using *.
Syntax:
from . import *
Knowing the current module name :
If we want to know the name of the current module, then we can use the attribute
“ name ” to print the name of the module with help of the print() function.
Example:
Print(“The current module name is:”,_name_)
Renaming a module :
Python provides us the flexibility to import a module with a specific name so that we can
use this name to use that module in our Python source file.
Syntax:
import <module-name> as <specific-name>
Example:
import calculation as cal
a = int(input("Enter a:"))
b = int(input("Enter b:"))
print("Sum = ",[Link](a,b))
reload() function
However, if you want to reload the already imported module to re-execute the top-level
code, python provides us the reload() function.
Syntax:
reload(<module-name>)
Example:
Namespacing :
- A namespace is a syntactic container that permits the same name to be used in different
modules or functions. Each module determines its own namespace, so we can use the
same name in multiple modules without causing an identification problem.
- Namespaces ensure that names are unique and do not clash with each other, preventing
naming conflicts.
- For example, functions such as area(r) and circum(r) are part of the module [Link].
We can also use same names in another module like “[Link]”. These functions are
called from these modules independently.
Uses of Namespaces :
- They help avoid naming conflicts by providing a unique identifier for each entity. This
ensures that variables, functions, or classes with the same name coexist without causing
issues.
- namespaces enhance code readability and maintainability by organizing related entities
together. They also enable modularity and code reusability using the same name in
different namespaces.
Types of namespace:
- Built-in Namespace: Python comes with a set of built-in namespaces that provide
access to pre-defined functions and objects. These will include names like ‘print’, ‘len’,
‘range’, etc. They are automatically available in every Python program without the
need for any explicit import statements.
- Global Namespace: They contains names that are accessible throughout the entire
program.
- Local Namespace: They are specific to a particular function or block of code. Create
Local namespaces when a function is called and destroyed when it completes its
execution.
Example:
gvar = 10 # global namespace
def fun1():
lvar = 20 # local namespace
def fun2():
lvar = 30 # local namespace
print(lvar)
print(lvar)
fun2()
print(gvar)
fun1()
Python packages
The packages in Python facilitate the developer with the application development
environment by providing a hierarchical directory structure where a package contains sub-
packages, modules, and sub-modules. The packages are used to categorize the application-
level code efficiently. When you've got a large number of Python classes (or "modules"),
you'll want to organize them into packages.
Steps to Create a Python Package
1. Create a directory and give it your package's name.
2. Put your module in it.
3. Create a __init__.py file in the directory
Note: The __init__.py file is necessary because with this file, Python will know that this
directory is a Python package directory other than an ordinary directory (or folder –
whatever you want to call it). Anyway, it is in this file where we'll write some import
statements to import modules from our brand new package.
Introduction to PIP
- We have created package in our system. There may be a situation where we want to
install packages that are not in our system and created by others residing in another
system. This can be done using the PIP tool.
- The Python Package Index is a repository of software for the Python programming
language. There are currently 1,15,120 packages here. If we need one package, we can
download it from this repository and install it on our system. This can be performed
using the PIP tool
- The PIP command is a tool for installing and managing packages, such as those found
in Python Packages Index repository ([Link]). To search for a package
say numpy, type the following:
Installing Packages via PIP
- To install a new package we can use the pip tool.
- To do this, first go to the path where Python software is installed and select the
folder "Scripts” which contains pip tool.
- Use this path in the command prompt and type the pip command.
- The requested package is downloaded from the internet from the
[Link] website.
- So you must have internet connection when you want to download, error will be
raised otherwise.
- To install package we write it as follow: pip install NumPy in the command
prompt
Check package is installed or not
Pip show packagename
Ex: pip show numpy
Uninstall package via pip
To uninstall package, we can use the pip tool as follows: pip uninstall numpy in the
command prompt.