Lab File-1st Sem
Lab File-1st Sem
AI & Robotics
Laboratory-I
Supratim Biswas
Intelligent Automation and
Robotics (1st Year)
Jadavpur University
Roll no.: 002110704007
INDEX
SL. NO. TITLE PAGES
M ATLAB stand for Matrix Laboratory developed by Math Works and is a software
package for high-performance mathematical computation, visualization, and
programming environment. It provides an interactive environment with hundreds of built-in
functions for technical computing, graphics, and animations.
1|Page
The following diagram shows the main features and capabilities of MATLAB
MATLAB
MATLAB
Programming
Language
User-written Functions
Built-in Functions
E E
X X
Graphics T T External Interface
Computations
R R (Mex-files)
2-D Graphics A Linear Algebra A
3-D Graphics Data Analysis Interface with C,
Color & Lighting F F Java, and Fortran
U Signal Processing U
Animation Polynomials &
Programs
N N
Audio & Video Interpolation
C C
T Quadrature T
I Solution of ODEs I
O O
N N
S S
Toolboxes
(Collections of Specialized Functions)
2|Page
MATLAB Components
Given below is the main screen of MATLAB.
Current Directory
Editor
Workspace
The Menu Bar and Tools contains various editing options and toolbox for doing various
tasks.
2. Current Directory
The Current Directory shows the contents of the current working directory. To use any m-
file double click and open it in the text editor. To change directory click on the folders or
use the Current Working Directory text box at the top and navigate to the required folder.
3. Editor
The Editor window is a simple text editor where we can load, edit and save complete
MATLAB programs.
3|Page
4. Workspace
The Workspace shows the list of variables that are currently defined, and tell us the type
of variable it is, like a simple scalar, vector or a matrix and the size of the arrays defined.
Double clicking the variable opens the variable in the array editor.
The Command Window is where we type in MATLAB commands. These can be simple
equations we want to evaluate, or more complex expressions involving MATLAB scripts
or functions. Pressing ↑ (upper arrow key) opens up the Command history window.
The Command History Window shows the commands we have entered in the past. We
can repeat any of these commands by double-clicking on them, or by dragging them from
the Command History Window into the Command Window. We can also scroll back to
previous commands by using the up arrow in the Command Window.
M File
Programming in MATLAB requires creating files where the code is written. M-Files are
ordinary ASCII text data written in MATLAB‟s language. Such files are called “M-Files”
because they have filename extension “.m” in the end (like program1.m). Without this
extension the data will not be interpreted by MATLAB.
1. M-File Scripts: Scripts do not accept input arguments or return output arguments.
They operate on data in workspace.
2. M-File Functions: Functions can accept input arguments and return output
arguments. Internal variables are local to the function.
1. Click the New Script icon on the Home tab on the environment. Else use
Ctrl+n keyboard shortcut to create a new script file.
2. A blank untitled file gets opened.
3. Save the Script using the Save icon on the Home tab or use Ctrl+s keyboard
shortcut and name the file correctly i.e., using .m extension.
4|Page
Programming in MATLAB
Variables
A variable is an abstract storage location paired with an associated symbolic name, which
contains some known or unknown quantity of information referred to as a value. In
MATLAB environment, every variable is an array or matrix. To create a variable enter the
name of variable in the command window and assign some values using the = operator.
E.g.:
>> a=100;
>> whos a;
a 1x1 8 double
>> b=false;
>> whos b;
b 1x1 1 logical
Matrices
A matrix is a two-dimensional array of numbers. In MATLAB, a matrix is created by
entering each row as a sequence of space or comma separated elements, and end of a row is
demarcated by a semicolon.
E.g.:
>> A = [1, 2, 3]
A=
1 2 3
5|Page
>> B = [1, 2, 3; 4, 5, 6]
B=
1 2 3
4 5 6
>> C = [1 2 3; 4 5 6; 7 8 9]
C=
1 2 3
4 5 6
7 8 9
Transposition Operation
>> D = [1; 2; 3]
D=
>> E = [1 2 3]'
E=
6|Page
Accessing Matrix Elements
Given Input Matrix:
>> A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9
>> A(1,3)
ans =
>> A(1)
ans =
>> A(2,2:3)
ans =
5 6
>> A(2,1:end)
ans =
4 5 6
>> A(2,1:2:3)
ans =
4 6
ans =
4 6
7|Page
Matrix Operations
Given two Input Matrices:
>> A = [1 2 3; 4 5 6; 7 8 9]
A=
1 2 3
4 5 6
7 8 9
>> B = [3 5 2; 5 2 8; 3 6 9]
B=
3 5 2
5 2 8
3 6 9
>> X = A + B
X=
4 7 5
9 7 14
10 14 18
>> Y = A - B
Y=
-2 -3 1
-1 3 -2
4 2 0
8|Page
>> Z = A * B
Z=
22 27 45
55 66 102
88 105 159
>> T = A'
T=
1 4 7
2 5 8
3 6 9
>> A = [1 2 3; 5 1 4; 3 2 -1]
A=
1 2 3
5 1 4
3 2 -1
>> x=A(1,:)
x=
1 2 3
>> y=A(:,3)'
y=
3 4 -1
9|Page
>> b=x.*y
b=
3 8 -3
>> c=x./y
c=
>> d=x.^y
d=
Matrix Concatenation
Given two Matrices:
>> X = [1 2]
X=
1 2
>> Y = [3 4]
Y=
3 4
>> A = [X Y]
A=
1 2 3 4
>> B = [X; Y]
B=
1 2
3 4
10 | P a g e
Q. Access the elements of the Matrix A using the following commands.
1. A = rand(4);
2. A(2,3)
3. A(:,2)
4. A(end,:)
5. A([1, 2], [1, 3])
6. A(1:2,3:end)
1. >> A=rand(4)
A=
2. >> A(2,3)
ans =
0.3404
3. >> A(:,2)
ans =
0.6551
0.1626
0.1190
0.4984
4. >> A(end,:)
ans =
11 | P a g e
5. >> A([1 ,2], [1, 3])
ans =
0.7094 0.9597
0.7547 0.3404
6. >> A(1:2,3:end)
ans =
0.9597 0.7513
0.3404 0.2551
Plotting Graphs
x=[1 3 5 7 9];
y=[10 2.9 38 41 15];
plot(x,y)
xlabel('time in secs')
ylabel('distance in cm')
title('Distance Covered by Robot')
12 | P a g e
Use of Subplot
subplot(2, 1, 1)
x=1:0.5:10;
y1=sin(x);
plot(x,y1)
subplot(2, 1, 2)
y2=sin(5*x);
plot(x,y2)
13 | P a g e
3D Plot
[x, y] = meshgrid(1:0.5:10,1:20);
z = sin(x) + cos(y);
surf(x, y, z)
14 | P a g e
Image Data Structure
An image is represented in form of matrices. There are two types of images:
Gray image: In digital images, grayscale means that the value of each pixel
represents only the intensity information of the light. Such images typically display
only the darkest black to the brightest white. In other words, the image contains only
black, white, and gray colors, in which gray has multiple levels.
It is represented by m×n matrix.
RGB image: RGB means Red Green Blue, i.e., the primary colors in additive color
synthesis. A RGB file consists in composite layers of Red, Green and Blue, each
being coded on 256 levels from 0 to 255.
It is represented by m×n×3 matrix.
15 | P a g e
Image I/O Display
% Read image (support bmp, jpg, png, ppm, etc)
I = imread(„img13.jpg‟);
% Save image
imwrite (I, „img13_out.jpg‟);
% Display image
imshow(I);
Input: Output:
Image Conversion
% Type conversion
I1 = im2double(I);
I2 = im2unit8(I);
Grayscale
16 | P a g e
% Resize image as 60% smaller
Ires = imresize (I, 0.6);
17 | P a g e
CHAPTER 2
Introduction to Python
Brief History
Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde &
Informatica (CWI) in Netherlands as a successor to the ABC programming language. The
ABC programming language was inspired by SETL which is a very high programming
language based on the mathematical theory of sets. The ABC programming language was
also capable of exception handling and interfacing with the Amoeba operating system.
Guido van Rossum was inspired by this language and motivated him to make his own version
of it. So he started developing a new language with all the features of the ABC programming
language and also added some new features. During his development of the new language he
wanted to give a name which was short and unique, so he named the language Python after
getting inspired from the Monty Python‟s Flying Circus, a BBC comedy series of late 1970s.
And in 1991 the first version of Python was released as Python 0.9.0.
Python 1.0: It was released in January 1994 which included some major new
features in the functional programming tools like lambda, reduce, filter and map.
Python 2.0: It was released in October 2000 and added new features like list
comprehensions, garbage collection system. Python 2.7 was the last version of Python
2.
Python 3.0: It was released on December 2008. It was designed to overcome the
flaws in the previous version of it. Changes included in Python 3 were in the print
function (now “print ( )”), input function (now “input ( )”) etc.
Currently Python 3 has become very popular and the new releases have become much bigger
and better. The latest release is Python 3.10.2 in January 2022.
18 | P a g e
Main Features of Python Programming Language
1. High Level language
2. Interpreted Language
Python is an interpreted language because Python code is executed line by line at a time
unlike other languages like C, C++, Java, etc. So as a result the debugging gets easier in
Python. The source code of python is converted into an immediate form called bytecode.
3. Easy Syntax
Python is very easy to learn the language as compared to other languages like C, C#,
Java, JavaScript, etc due to the easy syntax. The syntaxes are straight forward and easy to
learn. It does not require the use of semicolons or brackets rather is uses indentation to
specify different code blocks.
4. Dynamic Semantics
Python is a dynamically typed language which means there is no need for initialization of
variables. It automatically decides the type of variable at the run time.
In comparison to other programming languages like C, C++ and Java, Python is easier to
code due to its easy syntax. Also Python takes less no. of lines while coding to perform
same task compared to other languages. Hence Python is much simpler to code.
Python language is free available at the official website and can be downloaded easily.
Also the source codes, various packages are available widely and free to download
making is an Open Source language.
3. Portability
Python does not face any issue with various platforms. Codes are easily executable on
any platform having python installed and making it platform independent. So Python
codes are portable.
19 | P a g e
4. Huge Library Support
Python has a large standard library which provides a rich set of module and functions so
one can find and use various functions to complete the task. Also if any package is not
installed it can be installed easily using the command pip or pip3 and import the required
module.
5. Supports OOPs
Python supports Object Oriented Programming (OOPs) which bring the concepts of
classes and objects and also provide the advantages of using inheritance, polymorphism
and encapsulation techniques which provides the user the power of reusability of codes
and make tasks easier in less code.
As Python is an interpreted language it executes the code line by line which leads to slow
execution speed. Although Python is good for dynamic programming and has lot of
applications but when speed is the requirement for any project it is not preferred.
Since Python has flexibility with data types it and its ability to make coding simpler it
consumes a lot of memory and as a result Python has a poor memory management.
Applications of Python
1. Web Development.
2. Game Development.
3. Machine Learning and Artificial Intelligence.
4. Web Scraping Applications.
5. Audio and Video Applications.
6. Data Science and Data Visualization.
7. Desktop GUI etc.
20 | P a g e
Integrated Development Environments (IDE)
An IDE, or Integrated Development Environment, enables programmers to consolidate the
different aspects of writing a computer program. An IDEs increase programmer productivity
by combining common activities of writing software into a single application like editing
source code, building executables, and debugging.
21 | P a g e
CHAPTER 3
Python Fundamentals
Variables
A variable is a name given to a memory location that stores certain values. And these values
stored can be altered any time thus justifying the term variable. In Python a variable is
declared by a variable_name and a value assigned to it using the assignment operator (=).
E.g.: a = 100
b = „hello‟
Here a, b are two variables having values 100 and hello respectively. Hence we can also say
variables are containers that contain values.
Identifiers
An identifier is a name provided to recognize something let it be a variable, function, class,
module or any other object. It helps to differentiate one entity from one another.
Keywords
Keyword is a word having special meaning reserved by programming language. These are
reserved for special purpose and cannot be used as an identifier names.
22 | P a g e
Constants
A constant as the term suggests a type of variable whose value cannot be modified. Hence it
is fixed throughout the program.
E.g.: PI = 3.14
Literals
Literals are a raw data given in a variable or constant while programming. The types of
literals in Python are listed below:
1) String Literals
2) Numeric Literals
These are numeric data that belong to Integer, Float and Complex data types.
3) Boolean Literals
4) Special Literals
E.g.: a = 10
b = True
c = „Hello‟
Here 10, True and „Hello‟ are the literals (raw data assigned to variables).
Data Type
Data types are the classifications of different data. It represents the type of data stored in the
variable and what kind of operations is allowed to that data. As everything is an object in
Python, data types are actually classes and variables are instances of these classes.
1) Numeric
2) Sequence Type
3) Boolean
4) Set
5) Dictionary
23 | P a g e
Python – Data Types
Integer: Represented by int class and contains positive or negative whole numbers.
E.g.: 10, 100
Float: Represented by float class and contains data having decimal points.
E.g.: 2.35, 7.92
Complex: Represented by complex class and specified by real and imaginary part.
E.g.: -3+7j
Sequence Type
In Python, sequence is the ordered collection of similar or different data types. The several
sequence types in Python are as follows:
String
In Python, Strings are arrays of bytes representing Unicode characters. In Python there is
no character data type, a character is a string of length one. It is represented by str class.
It is immutable in nature. Strings are of two types: single line and multi-line string.
a = „„„Hello or “““Hello
24 | P a g e
String Slicing: This is a method by which a part of string is extracted. By this the string
elements can be accessed easily.
A [0] A [0 : 3]
In 1st case the position of the character is fetched and in 2nd case the starting and ending
index is provided from which the character is fetched from start index to end-1 index.
Similarly in a = „Hello‟
Slicing is also done by skipping the elements by the syntax: a [start : end : skip]. The the
count is done till end-1 and skip-1.
E.g.: a = „Hello‟
List
Lists are just like the arrays, declared in other language. Whereas in Python a List is very
flexible as it can store data of same and different types. Lists are mutable (can be
changed). Lists are of two types:
Considering a list A = [53, 57, 80, 71]. The elements are indexed as A = 0 1 2 3
53 57 80 7l
Then -5 -4 -3 -2
A [2] => 80 A [0:3] => [53, 57, 80] A [0:3:2] => [53, 80]
25 | P a g e
Tuple
Just like List, a Tuple is also an ordered collection of Python objects. Tuples are
immutable data type (cannot be modified). Tuple can also be homogeneous and
heterogeneous.
List Tuple
1. They are mutable data type. 1. They are immutable data type.
2. They are memory inefficient. 2. They are memory efficient.
3. Iteration within list is slower. 3. Iteration within a tuple is faster.
4. List has more in-built methods. 4. Tuple has less in-built methods.
Dictionary
It is a collection of key-value pairs. A Dictionary in Python is an unordered collection of data
values, used to store data values like a map. The key-values provided in dictionary makes it
more optimized. Each key-value pair in a Dictionary is separated by a „colon‟ and each key
are separated by a „comma‟. A dictionary is mutable and do not contain any duplicate keys.
E.g.: dict1 = {„Hi‟: „Hello‟} here the key is „Hi‟ and the value is „Hello‟.
A = {„Hi‟: „Hello‟,
26 | P a g e
Set
In Python, Set is an unordered collection of data type that is un-indexed, mutable and cannot
have any duplicate elements. Sets can be created by using built-in set ( ) function.
E.g.: s = {1, 2, 3, 4}
Type Conversion
Converting one data type to another data type is known as type conversion for the
programming simplicity. There are two types of Type Conversion in Python:
In implicit type conversion the Python interpreter automatically converts one data type to
another without any user involvement. It is also known as type coercion.
In explicit type conversion the data type is manually changes by the user as per their
requirement. It is also known as type casting.
27 | P a g e
Programming
NUMERIC
a=20
print(type (a))
Output: <class 'int'>
b=34.678
print(type(b))
Output: <class 'float'>
c=6+7j
print(type(c))
Output: <class 'complex'>
n=6>3
print(type(n))
print(n)
Output: <class 'bool'>
True
a=60
print(id(a))
Output: 140704887086592
a=70
print(id(a))
Output: 140704887086912
28 | P a g e
STRINGS
3. WAP to print the string 'hello'
a=('hello')
print(a)
Output: hello
b=("Anna's Diary")
print(b)
Output: Anna's Diary
c=('''Anna's home
is near Jadavpur''')
print(c)
Output: Anna's home
is near Jadavpur
f=("""Hi I am
Anna's sister""")
print(f)
Output: Hi I am
Anna's sister
d=('''She said," I am a
basketball
player"''')
29 | P a g e
print(d)
Output: She said," I am a
basketball
player"
s=('pearl')
print(s[3])
print(s[-1])
print(len(s))
print(s[0:4])
print(s[0:])
print(s[:5])
Output: r
l
5
pear
pearl
pearl
e=('Abracadabra')
print(e[0:6:1])
print(e[0:6:2])
print(e[0::2])
30 | P a g e
print(e[:11:2])
Output: Abraca
Arc
Arcdba
Arcdba
9. WAP to demonstrate the use of count, capitalize, upper, find, replace methods of
string
a=('hello')
d=('''She said," I am a
basketball
player"''')
print(a.count('l'))
print(a.capitalize())
print(a.upper())
print(d.find('basketball'))
print(d.replace('basketball','cricket'))
Output: 2
Hello
HELLO
22
She said," I am a
cricket
player"
a='hello'
print(id(a))
Output: 2923084221360
31 | P a g e
a='hi'
print(id(a))
Output: 2923085878064
LISTS
11. WAP to print a list and demonstrate indexing, slicing and slicing with skip value
mylist=[67,56,87,89,89,45]
print(mylist)
print(mylist[2])
print(mylist[-2])
print(mylist[0:3])
print(mylist[0:3:2])
Output: [67, 56, 87, 89, 89, 45]
87
89
[67, 56, 87]
[67, 87]
13. WAP to demonstrate append, sort, reverse, insert, remove and pop methods of list
a=[45,67,56,90,23]
a.append(77)
print(a)
Output: [45, 67, 56, 90, 23, 77]
32 | P a g e
a.sort() #not allowed in heterogeneous lists
print(a)
Output: [23, 45, 56, 67, 77, 90]
a.reverse()
print(a)
Output: [90, 77, 67, 56, 45, 23]
a.sort(reverse=True)
print(a)
Output: [90, 77, 67, 56, 45, 23]
a.insert(3,55)
print(a)
Output: [90, 77, 67, 55, 56, 45, 23]
a.remove(55)
print(a)
Output: [90, 77, 67, 56, 45, 23]
a.pop(3)
print(a)
Output: [90, 77, 67, 45, 23]
c=[4,6,7]
print(id(c))
Output: 2603599388160
33 | P a g e
c.insert(2,8)
print(c)
print(id(c))
Output: [4, 6, 8, 7]
2603599388160
TUPLES
15. WAP to create a tuple
tup=('orange','apple','apple', 45,78,78)
print(tup)
print(tup[0])
print(tup[-2])
print(tup[0:3])
print(tup[0:3:2])
Output: ('orange', 'apple', 'apple', 45, 78, 78)
orange
78
('orange', 'apple', 'apple')
('orange', 'apple')
print(tup.count('apple'))
Output: 2
print(tup.index('apple'))
Output: 1
t=('hi',90,6)
34 | P a g e
print(id(t))
Output: 1998257395584
t=('red', "green")
print(id(t))
Output: 1998255740544
18. WAP to show the memory occupied (in bytes) by lists and tuples
a=[3,5,7,9]
b=(3,5,7,9)
print(a.__sizeof__())
print(b.__sizeof__())
Output: 72
56
DICTIONARY
19. WAP to create a dictionary and print the corresponding keys and values and show
the way to access the values using keys
myDict={
'vital': 'important',
'Marks': [30, 55, 87, 90],
15 : 30
}
print(myDict.keys())
print(myDict.values())
print(myDict['vital'])
print(myDict['Marks'])
print(myDict[15])
Output: dict_keys(['vital', 'Marks', 15])
35 | P a g e
dict_values(['important', [30, 55, 87, 90], 30])
important
[30, 55, 87, 90]
30
Dict2={
'kind': 'benevolent',
'List': [30, 55, 87, 90],
'dict':{'happy':'joyful'}
}
print(Dict2['dict'])
print(Dict2['dict']['happy'])
Output: {'happy': 'joyful'}
joyful
21. WAP to change a value corresponding to a key in a dictionary and also show the use
of items method
abc={
'vital': 'important',
'Marks': [39, 54, 67, 98],
}
abc['Marks']=[35,67,94]
print(abc['Marks'])
print(abc.items())
Output: [35, 67, 94]
22. WAP to demonstrate the use of update method in dictionary in the form of adding a
key-value pair and modifying a value
36 | P a g e
myDict={
'vital': 'important',
'Marks': [30, 55, 87, 90],
15 : 30
}
dt={
'tiger':'carnivore'
}
myDict.update(dt)
print(myDict)
Output: {'vital': 'important', 'Marks': [30, 55, 87, 90], 15: 30, 'tiger': 'carnivore'}
dt3={
'vital':'essential'}
myDict.update(dt3)
print(myDict)
Output: {'vital': 'essential', 'Marks': [30, 55, 87, 90], 15: 30, 'tiger': 'carnivore'}
c={}
print(type(c))
myDict={
'vital': 'important',
15 : 30
37 | P a g e
print(id(myDict))
Output: 2002586541440
dt={
'tiger':'carnivore'
myDict.update(dt)
print(myDict)
print(id(myDict))
Output: {'vital': 'important', 'Marks': [30, 55, 87, 90], 15: 30, 'tiger': 'carnivore'}
2002586541440
25. WAP to access a value with and without using get method
#similarities
myDict={
'vital': 'important',
15 : 30
print(myDict.get('vital'))
print(myDict['vital'])
Output: important
important
#differences
myDict={
'vital': 'important',
print(myDict.get('flow'))
print(myDict['flow'])
Output: None
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print(myDict['flow'])
KeyError: 'flow'
SETS
a={1,2,3,4}
print(a)
Output: {1, 2, 3, 4}
b={5,6,7,8,5}
print(b)
Output: {8, 5, 6, 7}
d=set()
39 | P a g e
print(type(d))
d.add(6)
d.add(7)
print(d)
Output: <class 'set'>
{6, 7}
30. WAP to print the length of a set and also show the use of remove, pop and clear
methods
de={5,6,7,8}
print(len(de))
de.pop()
print(de)
de.remove(7)
print(de)
de.clear()
print(de)
Output: 4
{5, 6, 7}
{5, 6}
set()
b={5,6,7,8,5}
f={4, 9, 0, 6}
print(b.union(f))
print(b.intersection(f))
print(b.difference(f))
Output: {0, 4, 5, 6, 7, 8, 9}
40 | P a g e
{6}
{8, 5, 7}
d={6,7,8,9}
h={4,5,3,2}
d.update(h)
print(d)
Output: {2, 3, 4, 5, 6, 7, 8, 9}
de={5,7,8,9,0}
print(id(de))
de.remove(7)
print(id(de))
Output: 2389698173856
2389698173856
TYPE CONVERSION
34. WAP to show type conversion in a scenario where the user gives two inputs and
adds them
a=input('Enter a:')
b=input('Enter b:')
print('addition=', a+b)
Output: Enter a:100
Enter b:5
addition= 1005
a=int(input('Enter a:'))
41 | P a g e
b=int(input('Enter b:'))
print('addition=', a+b)
Output: Enter a:100
Enter b:5
addition=105
a=6.6
b=7
c=a+b
print(c)
Output: 13.6
42 | P a g e
38. WAP to convert a complex number to boolean
c=9+6j
print(bool(c))
Output: True
d=5>4
print(d)
print(int(d))
print(float(d))
print(complex(d))
Output: True
1
1.0
(1+0j)
40. WAP to take a binary string as input and convert it to an integer. Also convert the
integer output to a floating number
s='10010'
i=int(s,2)
print('%d is the converted integer' %i)
Output: 18 is the converted integer
e=float(i)
print('%f is the converted floating no.' %e)
Output: 18.000000 is the converted floating no.
n=print(bin(18))
43 | P a g e
a=f'{18:b}'
print('%s is the converted string.' %a)
c=f'{18:06b}'
print('%s is the converted string.' %c)
Output: 0b10010
10010 is the converted string.
010010 is the converted string.
k='509'
j=int(k)
print('%d is the converted integer' %j)
Output: 509 is the converted integer
g=789
k=str(g)
print('%s is the string' %k)
Output: 789 is the string
h='A'
l='%'
g=ord(h)
b=ord(l)
print('%d is the output' %g)
print('%d is the output' %b)
Output: 65 is the output
37 is the output
44 | P a g e
45. WAP to return a character from ASCII number
g=chr(65)
print('%s is the character' %g)
Output: A is the character
k=hex(56)
print('%s is the output' %k)
Output: 0x38 is the output
j=oct(56)
print('%s is the output' %j)
Output: 0o70 is the output
h='0F'
dec=int(h,16)
print(dec)
Output: 15
o='24'
de=int(o,8)
print(de)
Output: 20
48. WAP to convert a string into a list, tuple and set and vice versa
s='important'
l=list(s)
45 | P a g e
print('list is:',l)
Output: list is: ['i', 'm', 'p', 'o', 'r', 't', 'a', 'n', 't']
t=tuple(s)
print('tuple is:',t)
Output: tuple is: ('i', 'm', 'p', 'o', 'r', 't', 'a', 'n', 't')
s2=set(s)
print('set is:',s2)
Output: set is: {'t', 'm', 'i', 'o', 'p', 'a', 'r', 'n'}
l=[6,7,8,9]
j=str(l)
print(j)
print(type (j))
Output: [6, 7, 8, 9]
<class 'str'>
g=(5,6,7,8)
r=str(g)
print(r)
print(type (r))
Output: (5, 6, 7, 8)
<class 'str'>
f={8,9,5}
h=str(f)
print(h)
print(type (h))
46 | P a g e
Output: {8, 9, 5}
<class 'str'>
k=tuple(d.keys())
print(k)
w=tuple(d.values())
print(w)
Output: ('pigeon', 5)
('bird', 25)
h=set(d.keys())
print(h)
f=set(d.values())
print(f)
Output: {5, 'pigeon'}
{25, 'bird'}
47 | P a g e
Python Fundamentals – Practice Sets
1. WAP a program that considers the string „COMFORTABLE‟ as an input and
produces the following output.
a) COMFORT
b) CFTL
c) comfortable
d) The number of „O‟ from the input string
Sol. a='COMFORTABLE'
print(a[0:7])
print(a[0:11:3])
print(a.lower())
print(a.count('O'))
Output:
COMFORT
CFTL
comfortable
2
2. WAP a program that considers the string „she sells seashells on the seashore‟ as
an input and produces the following output.
a) Index value of „o‟ belonging to the word „on‟ and „s‟ belonging to the word
„seashore‟.
b) The word „seashore‟ is replaced by „seaside‟.
c) The first alphabet of „she‟ is converted to capital format.
d) sssal
Output:
20 27
she sells seashells on the seaside
48 | P a g e
She sells seashells on the seashore
sssal
3. WAP to take a list of item: 10, 2, 5, 30, 80 as an input and perform the following
operations.
a) Print [10, 5, 80]
b) Add 7 to the list
c) Sort the list in descending order (after adding 7 to the list)
d) Remove 30 from the list by accessing its index value
e) Convert the output in (d) to a tuple and a set
Output:
[10, 5, 80]
[10, 2, 5, 30, 80, 7]
[80, 30, 10, 7, 5, 2]
[80, 10, 7, 5, 2]
Tuple is (80, 10, 7, 5, 2)
Set is {2, 5, 7, 10, 80}
4. WAP to take a tuple of items: „apple‟, „grape‟, 40, 30 as an input and perform
the following operations.
a) Print the index value of „grapes‟
b) Print („grapes‟, 30)
49 | P a g e
c) Print „apple‟ using the concept of negative indexing
Output:
1
('grapes', 30)
apple
5. Create a dictionary with the following key-value pairs and perform the
instructed operations
Key Values
„student‟ „Anita‟
„marks‟ (90, 70, 80, 65)
400 2
„Lion‟ „Carnivore‟
a) Print the value corresponding to the key „marks‟
b) Change the tuple of marks to (62, 75, 86, 98)
c) Update the dictionary with key-value pair „pen‟: „write‟
d) Access the value of key 400 using the get method
e) Convert the keys to a list and values to a tuple
Sol. d={
'student' : 'Anita',
'marks' : (90, 70, 80, 65),
400 : 2,
'Lion' : 'Carnivore'
}
print(d['marks'])
d['marks']=[62, 75, 86, 98]
print(d)
dt={
'pen':'write'
}
50 | P a g e
d.update(dt)
print(d)
print(d.get(400))
p=list(d.keys())
print(p)
w=tuple(d.values())
print(w)
Output:
(90, 70, 80, 65)
{'student': 'Anita', 'marks': [62, 75, 86, 98], 400: 2, 'Lion': 'Carnivore'}
{'student': 'Anita', 'marks': [62, 75, 86, 98], 400: 2, 'Lion': 'Carnivore', 'pen': 'write'}
2
['student', 'marks', 400, 'Lion', 'pen']
('Anita', [62, 75, 86, 98], 2, 'Carnivore', 'write')
6. WAP to take a set o items: 10, 20, 30, 40 as an input and perform the following
operations
a) Add 35 to the set and then remove 40 from the set
b) Find the union and difference of the above set with b = {25, 35, 30, 42, 10}
Sol. s={10, 20, 30, 40}
s.add(35)
s.remove(40)
print(s)
b={25, 35, 30, 42, 10}
print(s.union(b))
print(s.intersection(b))
Output:
{35, 10, 20, 30}
{35, 10, 42, 20, 25, 30}
{10, 35, 30}
51 | P a g e
CHAPTER 4
Operators
O perators are special symbol that describes the action that needs to be done on the
operands. It helps to derive information from data by manipulating them to obtain a
solution. Operators are the pillars of a program on which the logic is built in a specific
programming language. Python provides a variety of operators discussed below:
1. Arithmetic operator
Arithmetic operators are used to perform arithmetic operations between two operands. It
includes + (addition), - (subtraction), *(multiplication), /(divide), %(modulus), //(floor
division), and exponent (**) operators.
Operator Description
+ (Addition) It is used to add two operands.
- (Subtraction) It is used to subtract second operand from first.
/ (Divide) It returns the quotient after dividing the first operand by second operand. Result can be both
integer and float.
* (Multiplication) It is used to multiply two operands.
% (Modulus) It returns the remainder after dividing first operand by second operand.
** (Exponent) It is an exponent operator and returns the first operand power to the second operand.
// (Floor Division) It gives the floor value of the quotient produced by dividing the two operands.
2. Assignment operator
The assignment operators are used to assign the value of the right expression to the left
operand. It includes =, +=, −=, ∗=, /=, % =, ∗∗=, //=.
Operator Description
= It assigns the value of right expression to the left operand.
+= It increases the value of the left operand by the value of right operand assigns it back to left
operand.
−= It decreases the value of the left operand by the value of right operand assigns it back to left
operand.
∗= It multiplies the value of left operand by the value of right operand and assigns the modified
value back to left operand.
/= It divides the value of the left operand by the value of the right operand and assigns the
modified value back to the left operand.
%= It divides the value of the left operand by the value of the right operand and assigns the
reminder back to the left operand.
∗∗= The exponential value of left operand to power of right operand and assigns it back to left
operand.
//= The floor value of the quotient is assigned back to left operand after the division of both left
and right operands.
52 | P a g e
3. Comparison operator
Comparison operators are used to comparing the value of the two operands and returns
Boolean true or false accordingly. It includes ==, ! =, <=, >=, >, <.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition becomes
true.
>= If the first operand is greater than or equal to the second operand, then the condition becomes
true.
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
4. Logical operator
The logical operators are used primarily in the expression evaluation to make a decision.
Python supports the following logical operators. It includes and, or, not.
Operator Description
and If both the expression are true, then the condition will be true.
or If one of the expressions is true, then the condition will be true.
not If an expression a is true, then not (a) will be false and vice versa.
5. Bitwise operator
The bitwise operators perform bit by bit operation on the values of the two operands. It
includes & (binary AND), | (binary OR), ^ (binary XOR), ~ (negation), ≪ (left shift), ≫
(right shift).
Operator Description
& (binary AND) If both the bits at the same place in two operands are 1, then 1 is copied to the result.
Otherwise, 0 is copied.
| (binary OR) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.
^ (binary XOR) The resulting bit will be 1 if both the bits are different; otherwise, the resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit will be
1 and vice versa.
≪ (left shift) The left operand value is moved left by the number of bits present in the right operand.
≫ (right shift) The left operand is moved right by the number of bits present in the right operand.
53 | P a g e
6. Identity operator
The identity operators are used to decide whether an element certain class or type. It
includes is, is not.
Operator Description
is It is evaluated to be true if the reference present at both sides point to the same object.
is not It is evaluated to be true if the reference present at both sides do not point to the same object.
7. Membership operator
Python membership operators are used to check the membership of value inside a Python
data structure. If the value is present in the data structure, then the resulting value is true
otherwise it returns false.
Operator Description
in It is evaluated to be true if the first operand is found in the second operand (list, tuple, or
dictionary).
not in It is evaluated to be true if the first operand is not found in the second operand (list, tuple, or
dictionary).
54 | P a g e
Programming
ARITHMETIC OPERATORS
a,b=25,4
print('Addition:',a+b)
print('Subtraction:',a-b)
print('Multiplication:',a*b)
print('Division:',a/b)
print('Floor division:',a//b)
print('Remainder:',a%b)
print('Exponential:',a**b)
Output: Addition: 29
Subtraction: 21
Multiplication: 100
Division: 6.25
Floor division: 6
Remainder: 1
Exponential: 390625
ASSIGNMENT OPERATOR
a=20
add=2
sub=2
mul=2
div=20
rem=20
fl=70
55 | P a g e
expo=1
add+=a
print(add)
sub-=a
print(sub)
mul*=a
print(mul)
div/=a
print(div)
rem%=a
print(rem)
fl//=a
print(fl)
expo**=a
print(expo)
Output: 22
-18
40
1.0
0
3
1
COMPARISON OPERATOR
a,b=20,30
print(a==b)
print(a!=b)
print(a>b)
print(a<b)
56 | P a g e
print(a>=b)
print(a<=b)
Output: False
True
False
True
False
True
LOGICAL OPERATOR
a=True
b=False
print(a and b)
print(a or b)
print(not a)
print(not b)
Output: False
True
False
True
BITWISE OPERATOR
a=1
b=2
print(a & b)
print(a | b)
print(a ^ b)
print(~ b)
57 | P a g e
print(a << 1)
print(a >> 1)
Output: 0
3
3
-3
2
0
IDENTITY OPERATOR
a=[20 ,3 ,4]
b=[2,3,4]
print(a is b)
print(a is not b)
Output: False
True
MEMBERSHIP OPERATOR
a=[2, 3, 6]
print(2 in a)
print(3 not in a)
print(7 not in a)
Output: True
False
True
58 | P a g e
Operators – Practice Sets
1. WAP to enter a number and display its hexadecimal and octal equivalent as well
as its square root.
Output:
Enter a no.: 10
0xa
0o12
3.1622776601683795
Output:
Enter x coordinate: 3
Enter y coordinate: 4
Distance: 5.0
Output:
Enter radius r: 10
Area of circle: 314.0
59 | P a g e
4. WAP to convert temperature in Fahrenheit to Celsius.
Sol. f=int(input("Enter temperature in Fahrenheit: "))
c= (f-32) * 5/9
print("Temperature in Celsius: ",c)
Output:
Enter temperature in Fahrenheit: 108
Temperature in Celsius: 42.22222222222222
5. Find the output of the following code.
a. 100%(45/2)
b. print(3*‟7‟)
c. a=12
print(a<<3)
print(a>>2)
d. a=16
b=20
print(a^b)
e. x=10
x/=2
print(x)
f. a=(2, 6, 9, 7)
b=(5, 9, 3)
print(a is not b)
g. a=6
print(~a)
h. a=[3, 9, 8, 5]
print(5 in a)
print(10 in a)
Sol. a. 10.0
b. 777
c. 96
3
d. 4
e. 5.0
f. True
g. -7
h. True
False
60 | P a g e
CHAPTER 5
Decision Control Statements
D ecision control statements in Python are the statements that helps in controlling the
functioning of a block of code as per the user need. With the help of these statements
task becomes easier for the programmer. They are mainly of 2 types:
Branching
Loops
Branching
Decision making is the most important part for any programming languages. For making
decisions there has to be some conditions or statements based on which selection is done.
These statements are also called Decision control statements or branching statements. In
Python, decision making is performed by the following statements:
1. The if Statement.
The if statement is used to test a specific condition. If the condition is true, a block of
code (if-block) will be executed. The condition of if statement can be any valid logical
expression which can be either evaluated to True or False.
Syntax: if expression:
statement
Flow-Chart
Condition
True
61 | P a g e
2. The if-else Statement.
The if-else statement provides an else block combined with the if statement which is
executed when the condition results in False. If the condition is true, then the if-block is
executed. Otherwise, the else-block is executed.
Syntax: if condition:
#block of statements
else:
#another block of statements (else-block)
Flow-Chart
Condition
True
False
If Block
Else Block
The elif statement enables to check multiple conditions and execute the specific block of
statements depending upon the condition which results True among them.
Syntax: if expression_1:
#block of statements
elif expression_2:
#block of statements
else:
#block of statements
62 | P a g e
Flow-Chart
Condition
False
Condition
False
True
True Condition
True
If Block
The nested if-else statements are an if-else statement inside another if-else statement.
Syntax: if condition_1:
if condition_2:
#block of statements
else:
#block of statements
else:
#block of statements
63 | P a g e
Flow-Chart
Condition 1
True
False
Condition 2
True
Else Block_1
False
Loops
The flow of programs written in any programming language is sequential by default. But
sometime we may be required to alter the flow of program. The execution of a specific code
may need to be repeated again and again. For this purpose the concept of loops are required.
In Python, we have two types of loops:
The for loop in Python is used to iterate some statements or a part of the program again
and again until the last item in sequence is reached.
print(i, end= „ ‟ )
64 | P a g e
Flow-Chart
Item
from the
sequence
If last item in
sequence
reached loop
Next Item exits
Loop Body
The Python while loops execute the block of code until the given condition returns False.
It is also known as a pre-tested loop.
Flow-Chart
Test
Expression
Loop exits
when
True condition
is False
Loop Body
65 | P a g e
As the loops executes there are at times when we need to exit the loop as well according to
the need. To accomplish this task we have some control statements in Python that help in
controlling the loop as per our need. These statements are:
1. Break Statement
The break is a keyword in python which is used to bring the program control out of the
loop. The break statement breaks the loops one by one, i.e., in the case of nested loops, it
breaks the inner loop first and then proceeds to outer loops. In other words, we can say
that break is used to abort the current execution of the program and the control goes to the
next line after the loop.
if i==2:
break
Will give output => 0 1 2
2. Continue Statement
The continue statement in python is used to bring the program control to the beginning of
the loop. The continue statement skips the remaining lines of code inside the loop and
start with the next iteration.
3. Pass Statement
In Python, the pass keyword is used to execute nothing; it means, when we don't want to
execute code, the pass can be used to execute empty. If we want to bypass any code pass
statement can be used.
E.g.: i=1
while i>3:
pass
print('Hello')
Will give output => Hello
66 | P a g e
Programming
IF-ELSE STATEMENTS
3. WAP to convert the entered letters in uppercase if in lowercase and vice versa
ch=input('enter a character:')
if (ch>='A' and ch<='Z'):
ch=ch.lower()
print('lowercase is:',ch)
else:
ch=ch.upper()
print('uppercase is:',ch)
67 | P a g e
Output: enter a character:k
uppercase is: K
68 | P a g e
else:
print('imaginary roots')
Output: enter the value of a:10
enter the value of b:5
enter the value of c:1
imaginary roots
WHILE LOOP
i=0
while (i<=5):
print(i)
i=i+1
Output: 0
1
2
3
4
5
69 | P a g e
enter the value of n:10
sum= 55
n=int(input('enter n:'))
sum=0
order=len(str(n))
t=n
while n>0:
digit=n%10
sum+=digit**order
n=n//10
if (sum==t):
print('Armstrong Number')
else:
print('Not Armstrong Number')
Output: enter n:1634
Armstrong Number
n=int(input('enter n:'))
r=0
while (n>0):
digit=n%10
r=r*10+digit
n=n//10
print('reversed number',r)
Output: enter n:625
70 | P a g e
FOR LOOP
71 | P a g e
13. WAP to calculate the average and sum of first n natural numbers
sum is 15
average is 3.0
15. WAP to print the Fibonacci series for a given number of terms
72 | P a g e
else:
next=first+second
print(next)
first=second
second=next
Output: enter the no. of terms:4
0
1
1
2
SERIES
16. WAP to find the sum of the series 1+1/2+....+1/n
n=int(input('enter the number:'))
s=0
for i in range (1,n+1):
a=float(1/i)
s=s+a
print('the sum is',s)
Output: enter the number:5
the sum is 2.283333333333333
17. WAP to find the sum of series 1/(1^1)+ 1/(2^2) + 1/(3^3) + 1/(n^n)
n=int(input('enter the number:'))
s=0
for i in range (1,n+1):
a=float(1/(i**i))
s=s+a
print('sum is',s)
Output: enter the number:5
sum is 1.291263287037037
73 | P a g e
PATTERNS
18. WAP to print the following pattern
*****
*****
*****
*****
*****
for i in range (5):
for j in range (5):
print('*',end=' ')
print()
Output:
*****
*****
*****
*****
*****
Output:
*
**
***
****
*****
74 | P a g e
20. WAP to print the following pattern
*****
****
***
**
*
for i in range (5):
for j in range (i,5):
print('*',end=' ')
print()
Output:
*****
****
***
**
*
Output:
*
* *
* * *
* * * *
* * * * *
75 | P a g e
22. WAP to print the following pattern
*****
****
***
**
*
for i in range (5):
for j in range (i+1):
print(' ',end=' ')
for k in range (i,5):
print('*',end=' ')
print()
Output:
* * * * *
* * * *
* * *
* *
*
76 | P a g e
Output:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
for i in range (5):
for j in range (i+1):
print(' ',end=' ')
for k in range (i,4):
print('*',end=' ')
for l in range (i,5):
print('*',end=' ')
print()
Output:
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
25. WAP to print the following pattern
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
77 | P a g e
for i in range (4):
for j in range (i,5):
print(' ',end=' ')
for k in range (i):
print('*',end=' ')
for l in range (i+1):
print('*',end=' ')
print()
Output:
*
*
* *
* *
* * *
* * *
* * * *
* * * *
* * * * *
* * *
* * * *
* *
* * *
*
* *
*
26. WAP to print the following pattern
1
22
333
4444
55555
p=1
78 | P a g e
for i in range (5):
for j in range (i+1):
print(p,end=' ')
p+=1
print()
Output:
1
22
333
4444
55555
p=5
for i in range (5):
for j in range (i+1):
print(p,end=' ')
p-=1
print()
Output:
5
44
333
2222
11111
79 | P a g e
for i in range (5):
if(i%2==0):
print('1',end=' ')
else:
print('2',end=' ')
print()
Output:
1
22
111
2222
11111
p=1 #change
p=p+1 #change
80 | P a g e
print()
p=p-1 #change
print()
Output:
1
2 2
3 3 3 3
4 4 4 4 4 4
5 5 5 5 5 5 5 5
4 4 4 4 4 4
3 3 3 3
2 2
1
1
12
123
1234
12345
81 | P a g e
Output:
1
12
123
1234
12345
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
p=1
print(p,end=' ')
p=p+1
print()
Output:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
82 | P a g e
for i in range (5):
p=1 #change
for j in range (i,5):
print(' ',end=' ')
for k in range (i):
print(p,end=' ') #change
p+=1 #change
for l in range (i+1):
print(p,end=' ') #change
p-=1 #change
print()
Output:
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
83 | P a g e
Output:
1
1 2 3
1 2 3 4 5
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9
p=1
for i in range (4):
for j in range (i+1):
print(p,end=' ')
p=p+1
print()
Output:
1
23
456
7 8 9 10
BREAK STATEMENT
84 | P a g e
CONTINUE STATEMENT
36. WAP to print numbers from 1 to 6 skipping 5 using continue
for i in range (1,7):
if i==5:
continue
print(i)
Output: 1
2
3
4
6
PASS STATEMENT
85 | P a g e
Decision Control Statement – Practice Sets
1. WAP to print the multiplication table of n, where n is entered by the user
(consider the multiplication of n up to 10 i.e., n x 1, n x 2,......, n x 10).
Sol: n=int(input("Enter a no.:"))
for i in range (1,11):
print(n,' x ',i,' = ',n*i)
Output:
Enter a no.:2
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
86 | P a g e
else:
print("Wrong Input")
Output:
Enter a no.: 7
Prime no.
Output:
Enter no.: 2
Enter power: 4
16
Output:
Enter year: 2004
Leap year
87 | P a g e
𝟏 𝟐 𝒏
5. WAP to find the sum of the series:𝟐 + +∙∙∙∙∙∙∙∙∙∙∙∙∙∙ + 𝒏+𝟏 .
𝟑
Output:
Enter a no.:10
7.980122655122655
Output:
Enter a no.: 10
3025
Output:
Enter a no.: 10
385
88 | P a g e
8. WAP to check whether a given number is palindrome or not.
Sol: n=int(input("Enter a no.: "))
t=n
sum=0
while(n!=0):
r=n%10
sum=sum*10+r
n//=10
if(sum==t):
print("Palindrome")
else:
print("Not Palindrome")
Output:
Enter a no.: 121
Palindrome
Output:
Enter the character: O
Vowel
89 | P a g e
10. WAP to find the largest among three numbers.
Sol: a=int(input("Enter a no.: "))
b=int(input("Enter a no.: "))
c=int(input("Enter a no.: "))
if(a>=b)and(a>=c):
print(a," is largest")
elif(b>=a)and(b>=c):
print(b," is largest")
else:
print(c," is largest")
Output:
Enter a no.: 10
Enter a no.: 20
Enter a no.: 30
30 is largest
11. WAP that prompts the user to enter a number between 1 to 7 and then displays
the corresponding day of the week.
Sol: d={
1:"Monday",
2:"Tuesday",
3:"Wednesday",
4:"Thursday",
5:"Friday",
6:"Saturday",
7:"Sunday"
if n in d.keys():
90 | P a g e
print(d[n])
else:
print("Wrong Input")
Output:
Enter a no. (1-7): 5
Friday
while p!=q:
if p>q:
p-=q
else:
q-=p
print("GCD: ",p)
Output:
Enter a no.: 15
Enter a no.: 70
GCD: 5
13. WAP using while loop that asks the user for a number and prints a countdown
from that number to zero.
Sol: n=int(input("Enter a no.: "))
while(n>=0):
print(n)
n-=1
91 | P a g e
Output:
Enter a no.: 3
Countdown begins:
2
1
0
b) *
**
***
****
*****
****
***
**
*
c) * * * *
* * *
* *
*
* *
* * *
* * * *
Sol: a) p=1
for i in range(5):
for j in range(i,5):
print(end=" ")
for k in range(i+1):
print(p, end=" ")
92 | P a g e
p+=1
print()
Output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Output:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
93 | P a g e
c) for i in range(4):
for j in range(i+1):
print(end=" ")
for k in range(i,4):
print('*',end=" ")
print()
for i in range(3):
for j in range(i,3):
print(end=" ")
for k in range(i+2):
print('*',end=" ")
print()
Output:
* * * *
* * *
* *
*
* *
* * *
* * * *
94 | P a g e
CHAPTER 6
Functions
A Function is a block of organized and reusable program code that performs a single
specific and well defined task. Functions help break our program into smaller and
modular chunks. As the program grows larger and larger, functions make it more organized
and manageable.
Advantages:
1. Decomposing a complex problem into simpler pieces.
2. Improves the clarity of the code.
3. Makes the program reusable i.e., uses the principle DRY (Don‟t Repeat Yourself)
instead of WET (Write Everything Twice/ We Enjoy Typing).
Syntax: def function_name (arguments):
#function body
E.g.: Subtraction of two numbers using function.
def diff (x, y):
return x-y
x = 20
y = 10
print (diff (x, y))
Output: 10
Global Variable
A global variable is a variable declared in the main body and is accessible throughout the
entire program.
Local Variable
A local variable is variable declared within a specific block and is only accessible within that
block only.
95 | P a g e
Global Variable Local Variable
1. Defined in the main body 1. Defined within a function block
2. Accessed throughout the entire 2. Accessed only within the specific
program. function
3. Example: 3. Example:
n=5 def func( ):
def func( ): n=5
print(n) print(n)
func( ) func( )
print(n) print(n)
Output: Output:
5 5
5 error
print(n_outer) 11
print(m_inner) 10
inner( ) error
print(n_outer)
print(m_inner)
outer( )
In the above example when outer( ) is called it enters the outer( ) block where n_outer is
assigned 10. Then the inner( ) is called and enters the inner( ) block where m_inner is
assigned 11. Then both n_outer and m_inner is printed and inner( ) exits. Then n_outer is
printed for the outer( ) but there is error in printing m_inner as it is a local variable of inner( ).
96 | P a g e
Return Statement
A return statement is used to end the execution of the function call and returns the result to
the caller. The statements after the return statements are not executed.
Properties:
1. A function may or may not have a return a value (None is returned).
2. Written within a function.
3. Function exits after a return statement.
E.g.:
def d(s): def d( ):
print(s)
print(„Hi‟)
x = d(„Hi‟)
return
print(x)
print(„One‟)
Output:
d( )
Hi
print(„Hello‟)
None
Output:
Hi
Hello
Type of arguments
1. Required argument
def display(str):
print(str)
str = „Hello‟
display(str)
Output: Hello
97 | P a g e
2. Keyword argument
def display(s, x, y):
print(s)
print(x)
print(y)
display(x = 5, y = 3.5, s = „Hi‟)
Output:
Hi
5
3.5
Output:
Sara
50
12000
3. Default argument
def display(name, age = 9)
print(name)
print(age)
98 | P a g e
display(name = „Sara‟)
Output:
Sara
9
99 | P a g e
E.g.:
def sq(a):
return a*a
sq(3)
Output:
9
x = lambda a: a*a
x(3)
Output:
9
Special functions
1. Filter function
The filter( ) method filters the given sequence with the help of a function that tests each
element in the sequence to be true or not.
Syntax: filter (function, sequence)
E.g.: def func(i):
if i >= 3:
return i
j = filter (func, [2, 3, 4])
print(list(j))
Output: [3, 4]
100 | P a g e
2. Map function
The map( ) function returns a map object of the results after applying the given function
to each item of a given sequence.
Syntax: map (function, sequence)
E.g.: def func(i):
return i+3
x = map (func, [2, 3, 4])
print(tuple(x))
Output: (5, 6, 7)
3. Reduce function
The reduce( ) function is used to apply a particular function passed it its argument to all
of the sequence elements. The function is defined in “functools” modules.
Syntax: reduce (function, sequence)
E.g.: def a(x+y):
return x+y
s = reduce (a, [2, 4, 5])
print(s)
Output: 11
101 | P a g e
Recursion
A function that calls itself to solve a problem until a base condition is satisfied.
E.g.: def fact(x):
if x= =1 or x = =0:
return 1
else:
return (x * fact(x-1))
x = fact(3)
Output: 6
Advantages:
1. The code becomes neat and clean.
2. The composite task is broken to simpler problem.
3. It is mostly applicable for codes which are shorter and simpler.
Disadvantages:
1. The logic at times can be difficult.
2. The computational time is expensive.
3. It is hard to debug.
Recursion Iteration
1. Top down approach. 1. Bottom up approach.
2. All problems don‟t have recursive 2. All problems can be solved.
function.
3. Computational time expensive 3. Computational time is efficient.
Modules
A module contains definition for a variable or function etc. They are files with .py
extension and are accessed using import keyword.
E.g.: import math
print(„pi =‟, math.pi) # 1st way of import (directly)
from math import pi
print(„pi =‟, pi) #2nd way of import (using from keyword)
from math import sqrt as sq_root
print(sq_root(4)) #3rd way of import (using user-defined keyword)
102 | P a g e
Namespace
It is a system that has a unique name for each and every object in Python.
1. Global
2. Local
3. Built-in
Built-in
Namespace
Global Namespace
Local
Namespace
Package
A package is basically a directory with Python files and a file with the name __init__ . py.
This means that every directory inside of the Python path, which contains a file named
__init__ . py, will be treated as a package by Python. It is collections of modules in
Python.
E.g.: Numpy, Pandas, Matplotlib etc.
103 | P a g e
Programming
FUNCTIONS
1. WAP that subtracts two numbers using a function
def diff(x,y):
return x-y
x=20
y=5
print(diff(x,y))
Output: 15
3. WAP to demonstrate that the arguments may be passed in the form of expressions to
the called function
def op(i) :
print('hello',i)
op(5+2*3)
Output: hello 11
104 | P a g e
LOCAL AND GLOBAL VARIABLE
4. WAP to show the difference between local and global variable
a=40
print('Global variable',a)
def func(b):
n=6
print('local variable',n)
print('local variable',b)
func(5)
Output: Global variable 40
local variable 6
local variable 5
105 | P a g e
show()
Output: Good
day
106 | P a g e
NESTED FUNCTIONS
9. WAP to demonstrate nested functions
def func12():
n=9
print(n)
def conv():
m=99
print (m)
conv()
func12()
Output: 9
99
107 | P a g e
11. WAP to show the access of same variable name in nested function
def fout():
n=9
def fin():
n=90
print(n)
fin()
print(n)
fout()
Output: 90
9
RETURN STATEMENT
13. WAP where a function is used without return statement and also try to print the
return value
def display(st):
print(st)
x=display('hello') #assigning return value to a variable
print(x)
print(display('good day')) # without assigning return value to a variable
Output: hello
None
good day
108 | P a g e
None
14. WAP to show the flow of control after the return statement
def display2():
print('hello')
return
print ('hi')
display2()
print('hello again')
Output: hello
hello again
109 | P a g e
s=12000000
details(salary=s,name=n,age=a)
Output: name is: Sara
age is: 50
salary is: 12000000
110 | P a g e
English
('English',)
Ajay likes to read
LAMBDA FUNCTION
19. WAP to show how lambda function reduces the code size
x=lambda a: a*a
x(3)
def sq(a):
return a*a
sq(3)
Output: 9
9
21. WAP to show the use of lambda function with and without assigning to a variable
t=lambda x:x**2
print(t(3))
print((lambda x:x**2)(3))
Output: 9
9
111 | P a g e
22. WAP that passes lambda function as an argument to a function
def fn(f,n):
print(f(n))
a=lambda x:x**2
b=lambda x:x*3
fn(a,3)
fn(b,5)
Output: 9
15
23. WAP that uses a lambda function that receives no arguments but returns a result
x=lambda: sum(range(1,5))
print(x())
Output: 10
112 | P a g e
SPECIAL FUNCTIONS
26. WAP to show the use of filter function with and without lambda function
## syntax: filter(function,sequence)
def func(i):
if i>=3:
return i
j=filter(func,[2,3,4])
#print(j)
print (list(j))
j=filter(lambda i: (i>=3),[2,3,4])
print (tuple(j))
Output: [3, 4]
(3, 4)
27. WAP to show the use of map function with and without lambda function
## syntax: map(function,sequence)
def func(i):
return i+3
x=map(func,[2,3,4])
print (list(x))
x=map(lambda y: y+3,[2,3,4])
print (tuple(x))
Output: [5, 6, 7]
(5, 6, 7)
28. WAP to show the use of reduce function with and without lambda function
## syntax: reduce(function,sequence)
from functools import reduce
def a(x,y):
113 | P a g e
return x+y
s=reduce(a,[2,4,5])
print(s)
from functools import reduce
s=reduce(lambda x,y:x+y,[2,4,5])
print(s)
Output: 11
11
31. WAP that uses map and filter functions within reduce function
from functools import reduce
r=reduce(lambda x,y:x+y, map(lambda x:x+x, filter(lambda x: (x<=4),[2,3,4,5,6])))
print(r)
Output: 18
114 | P a g e
RECURSION
32. WAP to find the fatorial of a number using recursion
def fact(x):
if x==1 or x==0:
return 1
else:
return x*fact(x-1)
x=int(input('enter x:'))
print('factorial is:',fact(x))
Output: enter x:5
factorial is: 120
115 | P a g e
MODULES
34. WAP to show the concept of module
import sys
print('path',sys.path)
Output: path['',
'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python38\\Lib\\idlelib',
'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\USER\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\USER\\AppData\\Roaming\\Python\\Python38\\site-packages\\win32',
'C:\\Users\\USER\\AppData\\Roaming\\Python\\Python38\\site-packages\\win32\\lib',
'C:\\Users\\USER\\AppData\\Roaming\\Python\\Python38\\site-packages\\Pythonwin',
'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
116 | P a g e
37. WAP to create user-defined module and import and use it.
def display(): #(mymodule.py)
print('hi')
print('name of the module:',__name__)
str='welcome'
import mymodule
print('mymodule str=',mymodule.str)
mymodule.display()
Output: mymodule str= welcome
hi
name of the module: mymodule
import name1
import name2
result1=name1.r(10)
print(result1)
result2=name2.r(10)
print(result2)
Output: 20
100
117 | P a g e
39. WAP to create a user-defined module to calculate largest no. and import to use it
def greater(a,b): #(large.py)
if a>b:
return a
else:
return b
import large
print('largest:',large.greater(3,4))
Output: largest: 4
118 | P a g e
elif user_action == "scissors":
if computer_action == "paper":
print("Scissors cuts paper! You win!")
else:
print("Rock smashes scissors! You lose.")
Output: Enter a choice (rock, paper, scissors): rock
119 | P a g e
Functions – Practise Sets
1. WAP using function to check the relation between two numbers (i.e., if a=b or
a>b or a<b).
Sol: def relation(a,b):
if(a==b):
print(a,' = ',b)
elif(a>b):
print(a,' > ',b)
else:
print(a,' < ',b)
c=int(input("Enter 1st no.: "))
d=int(input("Enter 2nd no.: "))
relation(c,d)
Output:
10 < 20
Output:
Enter 1st no.: 5
Enter 2nd no.: 10
120 | P a g e
After swap 1st no.: 10
After swap 2nd no.: 5
3. WAP using function that takes in two arguments a and b returns the average of
its arguments.
Sol: def avg(a,b):
return (a+b)/2
c=int(input("Enter 1st no.: "))
d=int(input("Enter 2nd no.: "))
print("Average: ",avg(c,d))
Output:
Enter 1st no.: 2
Enter 2nd no.: 6
Average: 4.0
4. WAP using function and return statement to check whether a number is even
or odd.
Sol: def oddeven(a):
if(a%2==0):
return 'Even'
else:
return 'Odd'
n=int(input("Enter a no.: "))
print(oddeven(n))
Output:
Enter a no.: 100
Even
121 | P a g e
5. WAP using function that converts a given time in hours to minutes.
Sol: def hr_min(x):
return x*60
n=float(input("Enter time in hours: "))
print("Time in minutes: ",hr_min(n))
Output:
Enter time in hours: 2
Time in minutes: 120.0
6. WAP using function to calculate simple interest. Consider 12% rate of interest
for senior citizen and 105 rate of interest for rest of the category of customers.
Sol: def si(x,p,t):
if(x>=60):
r=12
return (p*r*t)/100
else:
r=10
return(p*r*t)/100
age=int(input("Enter age: "))
principle=float(input("Enter principle amount: "))
time=int(input("Enter time period: "))
print("Interest earned: ",si(x=age,p=principle,t=time))
Output:
Enter age: 60
Enter principle amount: 10000
Enter time period: 2
Interest earned: 2400.0
122 | P a g e
7. WAP to calculate the volume of a cuboid using default argument.
Sol: def vol(x,y,z):
return x*y*z
l=float(input("Enter length: "))
b=float(input("Enter breadth: "))
h=float(input("Enter height: "))
print("Volume : ",vol(l,b,h))
Output:
Enter length: 10
Enter breadth: 20
Enter height: 30
Volume : 6000.0
8. WAP using function to calculate the sum of the series 1/1! + 4/2! + 27/3! + .........
Sol: def series(n):
def fact(a):
if(a==1 or a==0):
return 1
else:
return a*fact(a-1)
s=0
for i in range(1,n+1):
s+=((i**i)/fact(i))
return s
x=int(input('Enter a no.: '))
print(series(x))
Output:
Enter a no.: 3
7.5
123 | P a g e
9. WAP using recursive function to calculate the GCD of two numbers.
Sol: def gcd(x,y):
if(y!=0):
return gcd(y, x%y)
else:
return x
a=int(input('Enter 1st no.: '))
b=int(input('Enter 2nd no.: '))
print("GCD : ",gcd(a,b))
Output:
Enter 1st no.: 100
Enter 2nd no.: 50
GCD : 50
Output:
Enter no. of terms: 10
Fibonacci series:
0 1 1 2 3 5 8 13 21 34
124 | P a g e
11. WAP that prints the absolute, square root and cube of a number using any in-
built module.
Sol: import math
a=int(input("Enter a no.: "))
print("Absoulute of no.: ",math.fabs(a))
print("Square root of no.: ",math.sqrt(math.fabs(a)))
print("Cube of no.: ",math.pow(a,3))
Output:
Enter a no.: -9
Absoulute of no.: 9.0
Square root of no.: 3.0
Cube of no.: -729.0
Output:
2 51 89 73 53 40 94 91 61 83
13. WAP using lambda function to find the sum of first 10 natural numbers.
Sol: import functools
a=[]
n=int(input('Enter a no.: '))
for i in range(1,n+1):
a.append(i)
sum=functools.reduce(lambda x,y: x+y,a)
print("Sum : ",sum)
Output:
Enter a no.: 10
Sum : 55
125 | P a g e