UNIT – III
FUNCTIONS, ARRAYS
Fruitful functions: return values, parameters, local and global scope, function composition,
recursion; Strings: string slices, immutability, string functions and methods, string module;
Python arrays, Access the Elements of an Array, array methods.
Functions, Arrays:
Fruitful functions:
We write functions that return values, which we will call fruitful functions. We have seen
the return statement before, but in a fruitful function the return statement includes a return
value. This statement means: "Return immediately from this function and use the following
expression as a return value."
(or)
Any function that returns a value is called Fruitful function. A Function that does not return
a value is called a void function
Return values:
The Keyword return is used to return back the value to the called function.
# returns the area of a circle with the given radius:
def area(radius):
temp = 3.14 * radius**2
return temp
print(area(4))
(or)
def area(radius):
return 3.14 * radius**2
print(area(2))
Sometimes it is useful to have multiple return statements, one in each branch of a PYTHON
PROGRAMMING III YEAR/II SEM MRCET
56
return -x
else:
return x
Since these return statements are in an alternative conditional, only one will be executed.
As soon as a return statement executes, the function terminates without executing any
subsequent statements. Code that appears after a return statement, or any other place the
flow of execution can never reach, is called dead code.
In a fruitful function, it is a good idea to ensure that every possible path through the program
hits a return statement. For example:
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
This function is incorrect because if x happens to be 0, both conditions is true, and the
function ends without hitting a return statement. If the flow of execution gets to the end of a
function, the return value is None, which is not the absolute value of 0.
>>> print absolute_value(0)
None
By the way, Python provides a built-in function called abs that computes absolute values.
# Write a Python function that takes two lists and returns True if they have at least one
common member.
def common_data(list1, list2):
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [1,2,3,4,5]))
print(common_data([1,2,3,4,5], [1,7,8,9,510]))
print(common_data([1,2,3,4,5], [6,7,8,9,10]))
Output:
C:\Users\MRCET\AppData\Local\Programs\Python\Python38-32\pyyy\[Link] PYTHON PROGRAMMING
III YEAR/II SEM MRCET
57
True
True
None
#-----------------
def area(radius):
b = 3.14159 * radius**2
return b
Parameters:
Parameters are passed during the definition of function while Arguments are passed during
the function call.
Example:
#here a and b are parameters
def add(a,b): #//function definition
return a+b
#12 and 13 are arguments
#function call
result=add(12,13)
print(result)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
25
Some examples on functions:
# To display vandemataram by using function use no args no return type
#function defination
def display():
print("vandemataram")
print("i am in main") PYTHON PROGRAMMING III YEAR/II SEM MRCET
58
#function call
display()
print("i am in main")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
i am in main
vandemataram
i am in main
#Type1 : No parameters and no return type
def Fun1() :
print("function 1")
Fun1()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
function 1
#Type 2: with param with out return type
def fun2(a) :
print(a)
fun2("hello")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
Hello
#Type 3: without param with return type
def fun3():
return "welcome to python"
print(fun3()) PYTHON PROGRAMMING III YEAR/II SEM MRCET
59
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
welcome to python
#Type 4: with param with return type
def fun4(a):
return a
print(fun4("python is better then c"))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
python is better then c
Local and Global scope:
Local Scope:
A variable which is defined inside a function is local to that function. It is accessible from
the point at which it is defined until the end of the function, and exists for as long as the
function is executing
Global Scope:
A variable which is defined in the main body of a file is called a global variable. It will be
visible throughout the file, and also inside any file which imports that file.
The variable defined inside a function can also be made global by using the global
statement.
def function_name(args):
.............
global x #declaring global variable inside a function
..............
# create a global variable PYTHON PROGRAMMING III YEAR/II SEM MRCET
60
x = "global"
def f():
print("x inside :", x)
f()
print("x outside:", x)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
x inside : global
x outside: global
# create a local variable
def f1():
y = "local"
print(y)
f1()
Output:
local
If we try to access the local variable outside the scope for example,
def f2():
y = "local"
f2()
print(y)
Then when we try to run it shows an error,
Traceback (most recent call last):
File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]", line
6, in <module> PYTHON PROGRAMMING III YEAR/II SEM MRCET
61
print(y)
NameError: name 'y' is not defined
The output shows an error, because we are trying to access a local variable y in a global
scope whereas the local variable only works inside f2() or local scope.
# use local and global variables in same code
x = "global"
def f3():
global x
y = "local"
x=x*2
print(x)
print(y)
f3()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
globalglobal
local
In the above code, we declare x as a global and y as a local variable in the f3(). Then,
we use multiplication operator * to modify the global variable x and we print
both x and y.
After calling the f3(), the value of x becomes global global because we used the x *
2 to print two times global. After that, we print the value of local variable y i.e local.
# use Global variable and Local variable with same name
x=5
def f4():
x = 10
print("local x:", x)
f4()
print("global x:", x) PYTHON PROGRAMMING III YEAR/II SEM MRCET
62
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
local x: 10
global x: 5
Function Composition:
Having two (or more) functions where the output of one function is the input for another. So
for example if you have two functions FunctionA and FunctionB you compose them by
doing the following.
FunctionB(FunctionA(x))
Here x is the input for FunctionA and the result of that is the input for FunctionB.
Example 1:
#create a function compose2
>>> def compose2(f, g):
return lambda x:f(g(x))
>>> def d(x):
return x*2
>>> def e(x):
return x+1
>>> a=compose2(d,e) # FunctionC = compose(FunctionB,FunctionA)
>>> a(5) # FunctionC(x)
12
In the above program we tried to compose n functions with the main function created.
Example 2:
>>> colors=('red','green','blue')
>>> fruits=['orange','banana','cherry']
>>> zip(colors,fruits) PYTHON PROGRAMMING III YEAR/II SEM MRCET
63
<zip object at 0x03DAC6C8>
>>> list(zip(colors,fruits))
[('red', 'orange'), ('green', 'banana'), ('blue', 'cherry')]
Recursion:
Recursion is the process of defining something in terms of itself.
Python Recursive Function
We know that in Python, a function can call other functions. It is even possible for the
function to call itself. These type of construct are termed as recursive functions.
Factorial of a number is the product of all the integers from 1 to that number. For example,
the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Following is an example of recursive function to find the factorial of an integer.
# Write a program to factorial using recursion
def fact(x):
if x==0:
result = 1
else :
result = x * fact(x-1)
return result
print("zero factorial",fact(0))
print("five factorial",fact(5))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
zero factorial 1
five factorial 120
----------------------
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1)) PYTHON PROGRAMMING III YEAR/II SEM MRCET
64
num = 4
print("The factorial of", num, "is", calc_factorial(num))
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
The factorial of 4 is 24
Strings:
A string is a group/ a sequence of characters. Since Python has no provision for arrays,
we simply use strings. This is how we declare a string. We can use a pair of single or
double quotes. Every string object is of the type ‘str’.
>>> type("name")
<class 'str'>
>>> name=str()
>>> name
''
>>> a=str('mrcet')
>>> a
'mrcet'
>>> a=str(mrcet)
>>> a[2]
'c'
>>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns it to letter. The
expression in brackets is called an index. The index indicates which character in the
sequence we want
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
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.
Slice out substrings, sub lists, sub Tuples using index.
Syntax:[Start: stop: steps]
Slicing will start from index and will go up to stop in step of steps.
Default value of start is 0, PYTHON PROGRAMMING III YEAR/II SEM MRCET
65
Stop is last index of list
And for step default is 1
For example 1−
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character print
str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Output:
Hello World!
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:] PYTHON PROGRAMMING III YEAR/II SEM MRCET
66
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'
Immutability:
It is tempting to use the [] operator on the left side of an assignment, with the intention of
changing a character in a string.
For example:
>>> greeting='mrcet college!'
>>> greeting[0]='n'
TypeError: 'str' object does not support item assignment
The reason for the error is that strings are immutable, which means we can’t change an
existing string. The best we can do is creating a new string that is a variation on the original:
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> new_greeting
'Jello, world!'
Note: The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator PYTHON PROGRAMMING III YEAR/II SEM MRCET
67
String functions and methods:
There are many methods to operate on String.
[Link] Method name Description
1. isalnum() Returns true if string has at least 1 character and all
characters are alphanumeric and false otherwise.
2. isalpha() Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise.
3. isdigit() Returns true if string contains only digits and false
otherwise.
4. islower() Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false
otherwise.
5. isnumeric() Returns true if a string contains only numeric
characters and false otherwise.
6. isspace() Returns true if string contains only whitespace
characters and false otherwise.
7. istitle() Returns true if string is properly “titlecased” and
false otherwise.
8. isupper() Returns true if string has at least one cased character and all
cased characters are in uppercase
and false otherwise.
9. replace(old, new
[, max])
Replaces all occurrences of old in string with new
or at most max occurrences if max given.
10. split() Splits string according to delimiter str (space if not
provided) and returns list of substrings;
11. count() Occurrence of a string in another string
12. find() Finding the index of the first occurrence of a string
in another string
13. swapcase() Converts lowercase letters in a string to uppercase
and viceversa
14. startswith(str,
beg=0,end=le
n(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.
Note:
All the string methods will be returning either true or false as the result
1. isalnum(): PYTHON PROGRAMMING III YEAR/II SEM MRCET
68
Isalnum() method returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
Syntax:
[Link]()
Example:
>>> string="123alpha"
>>> [Link]() True
2. isalpha():
isalpha() method returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
Syntax:
[Link]()
Example:
>>> string="nikhil"
>>> [Link]()
True
3. isdigit():
isdigit() returns true if string contains only digits and false otherwise.
Syntax:
[Link]()
Example:
>>> string="123456789"
>>> [Link]()
True
4. islower():
Islower() returns true if string has characters that are in lowercase and false otherwise.
Syntax: PYTHON PROGRAMMING III YEAR/II SEM MRCET
69
[Link]()
Example:
>>> string="nikhil"
>>> [Link]()
True
5. isnumeric():
isnumeric() method returns true if a string contains only numeric characters and false
otherwise.
Syntax:
[Link]()
Example:
>>> string="123456789"
>>> [Link]()
True
6. isspace():
isspace() returns true if string contains only whitespace characters and false otherwise.
Syntax:
[Link]()
Example:
>>> string=" "
>>> [Link]()
True
7. istitle()
istitle() method returns true if string is properly “titlecased”(starting letter of each word is
capital) and false otherwise
Syntax:
[Link]() PYTHON PROGRAMMING III YEAR/II SEM MRCET
70
Example:
>>> string="Nikhil Is Learning"
>>> [Link]()
True
8. isupper()
isupper() returns true if string has characters that are in uppercase and false otherwise.
Syntax:
[Link]()
Example:
>>> string="HELLO"
>>> [Link]()
True
9. replace()
replace() method replaces all occurrences of old in string with new or at most max
occurrences if max given.
Syntax:
[Link]()
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('Nikhil','Neha')
'Neha Is Learning'
[Link]()
split() method splits the string according to delimiter str (space if not provided)
Syntax:
[Link]()
Example:
>>> string="Nikhil Is Learning"
>>> [Link]() PYTHON PROGRAMMING III YEAR/II SEM MRCET
71
['Nikhil', 'Is', 'Learning']
[Link]()
count() method counts the occurrence of a string in another string Syntax:
[Link]()
Example:
>>> string='Nikhil Is Learning'
>>> [Link]('i')
[Link]()
Find() method is used for finding the index of the first occurrence of a string in another
string
Syntax:
[Link](„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('k')
[Link]()
converts lowercase letters in a string to uppercase and viceversa
Syntax:
[Link](„string‟)
Example:
>>> string="HELLO"
>>> [Link]()
'hello'
[Link]()
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. PYTHON PROGRAMMING III
YEAR/II SEM MRCET
72
Syntax:
[Link](„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('N')
True
[Link]()
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.
Syntax:
[Link](„string‟)
Example:
>>> string="Nikhil Is Learning"
>>> [Link]('g')
True
String module:
This module contains a number of functions to process standard Python strings. In recent
versions, most functions are available as string methods as well.
It’s a built-in module and we have to import it before using any of its constants and classes
Syntax: import string
Note:
help(string) --- gives the information about all the variables ,functions, attributes and classes
to be used in string module.
Example:
import string
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print([Link]) PYTHON PROGRAMMING III YEAR/II SEM MRCET
73
print([Link])
#print([Link])
print([Link])
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
=========================================
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Python String Module Classes
Python string module contains two classes – Formatter and Template.
Formatter
It behaves exactly same as [Link]() function. This class becomes useful if you want to
subclass it and define your own format string syntax.
Syntax: from string import Formatter
Template
This class is used to create a string template for simpler string substitutions
Syntax: from string import Template
Python arrays:
Array is a container which can hold a fix number of items and these items should be of the
same type. Most of the data structures make use of arrays to implement their algorithms.
Following are the important terms to understand the concept of Array.
Element− Each item stored in an array is called an element.
Index − Each location of an element in an array has a numerical index, which is used
to identify the element.
Array Representation PYTHON PROGRAMMING III YEAR/II SEM MRCET
74
Arrays can be declared in various ways in different languages. Below is an illustration.
Elements
Int array [10] = {10, 20, 30, 40, 50, 60, 70, 80, 85, 90}
Type Name Size Index 0
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at
index 6 as 70
Basic Operations
Following are the basic operations supported by an array.
Traverse − print all the array elements one by one.
Insertion − Adds an element at the given index.
Deletion − Deletes an element at the given index.
Search − Searches an element using the given index or by the value.
Update − Updates an element at the given index.
Array is created in Python by importing array module to the python program. Then the
array is declared as shown below.
from array import *
arrayName=array(typecode, [initializers])
Typecode are the codes that are used to define the type of value the array will hold. Some
common typecodes used are:
Typecode Value
b Represents signed integer of size 1 byte/td>
B Represents unsigned integer of size 1 byte PYTHON PROGRAMMING III YEAR/II SEM MRCET
75
c Represents character of size 1 byte
i Represents signed integer of size 2 bytes
I Represents unsigned integer of size 2 bytes
f Represents floating point of size 4 bytes
d Represents floating point of size 8 bytes
Creating an array:
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)
Output:
>>>
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/[Link]
10
20
30
40
50
Access the elements of an Array:
Accessing Array Element
We can access each element of an array using the index of the element.
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1[0])
print (array1[2]) PYTHON PROGRAMMING III YEAR/II SEM MRCET
76
Output:
RESTART: C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link]
10
30
Array methods:
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list PYTHON PROGRAMMING III YEAR/II SEM MRCET
77
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
Example:
>>> college=["mrcet","it","cse"]
>>> [Link]("autonomous")
>>> college
['mrcet', 'it', 'cse', 'autonomous']
>>> [Link]("eee")
>>> [Link]("ece")
>>> college
['mrcet', 'it', 'cse', 'autonomous', 'eee', 'ece']
>>> [Link]()
'ece'
>>> college
['mrcet', 'it', 'cse', 'autonomous', 'eee']
>>> [Link](4)
'eee'
>>> college
['mrcet', 'it', 'cse', 'autonomous']
>>> [Link]("it")
>>> college
['mrcet', 'cse', 'autonomous']