0% found this document useful (0 votes)
15 views

Lab File-1st Sem

Uploaded by

Rupayan Halder
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lab File-1st Sem

Uploaded by

Rupayan Halder
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 127

2021-22

AI & Robotics
Laboratory-I

Supratim Biswas
Intelligent Automation and
Robotics (1st Year)
Jadavpur University
Roll no.: 002110704007
INDEX
SL. NO. TITLE PAGES

Chapter 1: Introduction to MATLAB 1-17


1
Chapter 2: Introduction to Python 18-21
2
Chapter 3: Python Fundamentals 22-27
3
Programming 28-47

Python Fundamentals - Practice Sets 48-51

Chapter 4: Operators 52-54


4
Programming 55-58

Operators - Practice Sets 59-60

Chapter 5: Decision Control Statements 61-66


5
Programming 67-85

Decision Control Statements - Practice Sets 86-94

Chapter 6: Functions 95-103


6
Programming 104-119

Functions - Practice Sets 120-125


CHAPTER 1
Introduction to MATLAB

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.

MATLAB is a modern programming language environment, and it has refined data


structures, includes built-in editing and debugging tools, and supports object-oriented
programming. Besides an environment, MATLAB is also a programming language. As the
name contains the word Matrix, MATLAB does all computing based on mathematical
matrices and arrays. MATLAB holds all type of variable in form of an array only whether it
is an integer, character or string type variable.

MATLAB is widely used in various disciplines of Engineering, Science and Economics

Few applications of MATLAB are listed below:

1. Statistics and Machine Learning


2. Curve Fitting
3. Control Systems
4. Signal Processing
5. Mapping
6. Deep Learning
7. Financial analysis
8. Image Processing
9. Text analysis
10. Electric Vehicle designing
11. Aerospace
12. Audio Toolbox

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)

 Signal Processing  Image Processing


 Statistics  Splines
 Control System  Robust Control
 System Identification  m-Analysis &
 Neural Networks Synthesis
 Communications  Optimization
 Symbolic Mathematics  Financial and many
more

2|Page
MATLAB Components
Given below is the main screen of MATLAB.

Menu Bar and Tools

Current Directory

Editor

Workspace

Command window and


Command History

1. Menu Bar and Tools

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.

5. Command window and Command History

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.

Types of M-Files are as follows:

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.

To create a new M-File in MATLAB follow the below steps:

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;

Name Size Bytes Class Attributes

a 1x1 8 double

>> b=false;

>> whos b;

Name Size Bytes Class Attributes

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

>> A(2,[1 3])

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

Element-wise Matrix operation


Given Input Matrix:

>> 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=

0.3333 0.5000 -3.0000

>> d=x.^y

d=

1.0000 16.0000 0.3333

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)

Sol: Let the input matrix A be:

1. >> A=rand(4)

A=

0.7094 0.6551 0.9597 0.7513

0.7547 0.1626 0.3404 0.2551

0.2760 0.1190 0.5853 0.5060

0.6797 0.4984 0.2238 0.6991

2. >> A(2,3)

ans =

0.3404

3. >> A(:,2)

ans =

0.6551

0.1626

0.1190

0.4984

4. >> A(end,:)

ans =

0.6797 0.4984 0.2238 0.6991

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.

Format of the image is:

 [0, 255] uint8


 [0, 1] double

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);

% Convert from RGB to grayscale


I3 = rgb2gray(I);
imshow(I3);

Grayscale

16 | P a g e
% Resize image as 60% smaller
Ires = imresize (I, 0.6);

% Crop image from user‟s input


imshow(I);
Rect = getrect;
Icrp = imcrop(I, Rect);
imshow(Icrp)

% Rotate image by 45 degrees


Before Crop
Irot = imrotate (I,45);

45 degree rotated After Crop

17 | P a g e
CHAPTER 2
Introduction to Python

P ython is an interpreted high-level general-purpose programming language. Its design


philosophy emphasizes code readability with its use of significant indentation.
Its language constructs as well as its object-oriented approach aim to help programmers write
clear, logical code for small and large-scale projects.

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.

The further developments in the Python versions are as follows:

 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

Python is a high-level language. So when we write programs in python, we don‟t require


remembering the system architecture and also not require managing the memory.

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.

Advantages of using Python


1. Simplicity

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.

2. Open Source Language

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.

Disadvantages of using Python


1. Slow Speed

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.

2. Poor Memory Management

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.

Organizations using Python


1. Google
2. YouTube.
3. Dropbox.
4. Pixar.
5. Netflix.
6. Intel.
7. Facebook 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.

Main Features of an IDE:

1. Code Editor: Text editor where we can write code.


2. Syntax Highlighting: This features helps in good visualization of the code by
highlighting the syntaxes.
3. Auto Completion: This feature helps us in writing code by writing small phrase
automatically completes the desired syntax according to the coder.
4. Debugger: Helps debugging errors in program.
5. Compiler / Interpreter: Compiler executes the code at once and Interpreter executes
the code line by line.
6. Language Support: IDE can support single or multiple programming languages.

Some common Python IDE‟s are listed below:

1. IDLE (default Python IDE).


2. Jupyter Notebook
3. Thonny.
4. Atom.
5. PyCharm.
6. Spyder.
7. Sublime Text.
8. Visual Studio Code.

IDLE Jupyter Thonny Atom

Spyder Sublime Text VS Studio Code PyCharm

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.

Rules of using Identifiers:

1) An identifier should always start with an underscore ( _ ) or a letter (A-Z / a-z). An


identifier starting with a digit is invalid.
2) The rest part of the characters can be an underscore ( _ ) or letters (A-Z / a-z) or digits
(0-9).
3) An identifier name is case sensitive (e.g. myVar ≠ MyVar).
4) Punctuations symbols (#, !, @, $ etc) are not allowed.
5) While naming an identifier whitespaces are not allowed.
6) Keywords cannot be used as an identifier.

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.

E.g.: if, else elif, def, for, while, import etc

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

It is formed by enclosing text within single as well as double quotes.

2) Numeric Literals

These are numeric data that belong to Integer, Float and Complex data types.

3) Boolean Literals

This literal have only two values True or False.

4) Special Literals

Python has one special literal i.e., None.

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.

Built-in data types in Python:

1) Numeric
2) Sequence Type
3) Boolean
4) Set
5) Dictionary

23 | P a g e
Python – Data Types

Numeric Dictionary Boolean Set Sequence Type

Integer Float String Tuple

Complex Number List

Numeric Data Type


In Python, numeric data type represent the data which has numeric value, it can be integer,
floating number or complex number. These values are defined as int, float and complex class
in Python. And have immutable property (cannot be changed).

 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.

E.g.: a = „Hello‟ or “Hello” i.e., single line string

a = „„„Hello or “““Hello

Hi‟‟‟ Hi””” i.e., multi-line string

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.

E.g.: let the string be A = „Hello‟.

A= 0 1 2 3 4 The string A is been indexed 0 to 4 and -1 to -5


H e l l o
-5 -4 -3 -2 -1

A [position] A [start : end]

A [0] A [0 : 3]

=> H => Hel

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‟

a[0 : 5] => Hello and a[ : 5] => 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‟

a[0 : 3 : 1] => Hel and a[0 : 3 : 2] => Hl

 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:

1. Homogenous List: contain same type of data.


2. Heterogeneous List: contain different type of data.

List is created by placing the sequence inside square brackets [ ].

E.g.: A = [20, 30, 10, 40] i.e., homogeneous list

B = [„hi‟, 10, „abc‟] i.e., heterogeneous list

Elements in list can be accessed by list indexing.

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.

E.g.: a = („apple‟, 80, 90) i.e., heterogeneous tuple

b = (80, 81, 82) i.e., homogeneous tuple

Similarities between List and Tuple:

1. List and Tuple can be both homogenous and heterogeneous.


2. They both are ordered. And the elements can be accessed by indexing.
3. They both can contain duplicates values.

Differences between List and Tuple:

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‟.

Accessing the keys and values in a dictionary.

A = {„Hi‟: „Hello‟,

„List‟: [10, 20, 30]}

print (a.key( )) => „Hi‟, „List‟

print (a.values( )) => „Hello‟, [10, 20, 30]

print (a[„Hi‟]) => „Hello‟

print (a[„List‟]) => [10, 20, 30]

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:

 Implicit Type Conversion

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.

 Explicit Type Conversion

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

1. WAP to demonstrate the numeric data types

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

2. WAP to show that numeric data type is immutable

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

4. WAP to show the use of double quotes in printing strings

b=("Anna's Diary")
print(b)
Output: Anna's Diary

5. WAP to print multi-line string

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

6. WAP to show the use of different quotes in strings

d=('''She said," I am a
basketball
player"''')

29 | P a g e
print(d)
Output: She said," I am a
basketball
player"

k=("""He said, "Hi".""")


print(k)
Output: He said, "Hi".

7. WAP to demonstrate different types of String Slicing

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

8. WAP to demonstrate different types of String Slicing with Skip Elements

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"

10. WAP to show that strings are immutable

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]

12. WAP to print a heterogeneous list

hetero=['orange', 67, 'apple', 'Sara', 88, False]


print(hetero)
Output: ['orange', 67, 'apple', 'Sara', 88, False]

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]

14. WAP to show lists are mutable

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')

16. WAP to show the use of count and index methods

print(tup.count('apple'))
Output: 2

print(tup.index('apple'))
Output: 1

17. WAP to show that tuples are immutable

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

20. WAP to demonstrate the concept of nested dictionary

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]

dict_items([('vital', 'important'), ('Marks', [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'}

23. WAP to declare an empty Dictionary

c={}

print(type(c))

Output: <class 'dict'>

24. WAP to show dictionaries are mutable

myDict={

'vital': 'important',

'Marks': [30, 55, 87, 90],

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',

'Marks': [30, 55, 87, 90],

15 : 30

print(myDict.get('vital'))

print(myDict['vital'])

Output: important
important

#differences

myDict={

'vital': 'important',

'Marks': [30, 55, 87, 90],


38 | P a g e
15 : 30

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

26. WAP to print a set

a={1,2,3,4}
print(a)
Output: {1, 2, 3, 4}

27. WAP to show that sets cannot have duplicate items

b={5,6,7,8,5}
print(b)
Output: {8, 5, 6, 7}

28. WAP to print a heterogeneous set

c={'hi', 78.99, True}


print(c)
Output: {True, 'hi', 78.99}

29. WAP to declare an empty set and add some elements to it

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()

31. WAP to demonstrate union, difference and intersection methods

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}

32. WAP to depict the update method

d={6,7,8,9}
h={4,5,3,2}
d.update(h)
print(d)
Output: {2, 3, 4, 5, 6, 7, 8, 9}

33. WAP to show sets are mutable

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

35. WAP to show implicit type conversion

a=6.6
b=7
c=a+b
print(c)
Output: 13.6

36. WAP to convert integer to float, boolean and complex


a=5
print(float(a))
print(complex(a))
print(bool(a))
Output: 5.0
(5+0j)
True

37. WAP to convert float to integer, boolean and complex


f=9.7
print(int(f))
print(complex(f))
print(bool(f))
Output: 9
(9.7+0j)
True

42 | P a g e
38. WAP to convert a complex number to boolean

c=9+6j
print(bool(c))
Output: True

39. WAP to convert boolean to integer, float and complex

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.

41. WAP to convert an integer to binary string

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.

42. WAP to convert a numerical string into an integer

k='509'
j=int(k)
print('%d is the converted integer' %j)
Output: 509 is the converted integer

43. WAP to convert an integer to a string

g=789
k=str(g)
print('%s is the string' %k)
Output: 789 is the string

44. WAP to return an ASCII value from character or symbol

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

46. WAP to convert 56 into hexadecimal and octal strings

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

47. WAP to convert hexadecimal and octal strings to integer

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'>

49. WAP to convert a dictionary to list, tuple and set


d= {
'pigeon':'bird',
5:25
}
p=list(d.keys())
print(p)
j=list(d.values())
print(j)
Output: ['pigeon', 5]
['bird', 25]

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

Sol. a='she sells seashells on the seashore'


print(a.find('on'),a.find('seashore'))
print(a.replace('seashore','seaside'))
print(a.capitalize())
print(a[0:20:4]

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

Sol. a=[10, 2, 5, 30, 80]


print(a[0:5:2])
a.append(7)
print(a)
a.sort(reverse=True)
print(a)
del a[1]
print(a)
t=tuple(a)
print('Tuple is',t)
s=set(a)
print('Set is',s)

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

Sol. t=('apple', 'grapes', 40, 30)


print(t.index('grapes'))
print(t[1:4:2])
print(t[-4])

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

1. WAP to demonstrate the different 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

2. WAP to demonstrate the different assignment operators

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

3. WAP to demonstrate different comparison operators

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

4. WAP to demonstrate different logical operators

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

5. WAP to demonstrate different bitwise operators

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

6. WAP to demonstrate different identity operators

a=[20 ,3 ,4]

b=[2,3,4]

print(a is b)

print(a is not b)

Output: False

True

MEMBERSHIP OPERATOR

7. WAP to demonstrate different membership operators

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.

Sol. a=int(input("Enter a no.: "))


print(hex(a))
print(oct(a))
print(a**(1/2))

Output:
Enter a no.: 10
0xa
0o12
3.1622776601683795

2. WAP to calculate distance between two points in x-y plane.


Sol. x=int(input("Enter x coordinate: "))
y=int(input("Enter y coordinate: "))
d=(x**2 + y**2)**(1/2)
print("Distance: ",d)

Output:
Enter x coordinate: 3
Enter y coordinate: 4
Distance: 5.0

3. WAP to calculate the area of a circle.


Sol. r=int(input("Enter radius r: "))
a=3.14*(r**2)
print("Area of circle: ",a)

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

False Block of Code

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

3. The elif Statement.

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

Statement 1 Statement 2 Statement 3

If Block

4. The nested if-else Statement.

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

Else Block_2 If Block_2

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:

1. The for loop.

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.

Syntax: for iterating_variable in sequence:


Statements
E.g.: for i in range (1,4):

print(i, end= „ ‟ )

will result in the output => 1 2 3

64 | P a g e
Flow-Chart

Item
from the
sequence
If last item in
sequence
reached loop
Next Item exits

Loop Body

2. The while loop.

The Python while loops execute the block of code until the given condition returns False.
It is also known as a pre-tested loop.

Syntax: while test_expression:


statements
E.g.: i=1
while(i<4):
print(i, end= „ ‟)
i+=1
will result in the output => 1 2 3

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.

E.g.: for i in range (0,5):


print(i, end= „ ‟)

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.

E.g.: for i in range (0, 5):


if i==2:
continue
print(i, end=' ')
Will give output => 0 1 3 4

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

1. WAP using if statement(s) to determine whether a person is eligible to vote

age=int(input('enter the age:'))


if (age>=18):
print('eligible to vote')
if (age<18):
print('not eligible to vote')
Output: enter the age:18
eligible to vote

2. WAP to check a number is even or odd

num=int(input('enter the number:'))


if (num%2==0):
print('even')
else:
print('odd')
Output: enter the number:21
odd

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

4. WAP to print a given no as positive, negative or zero

n=int(input('Enter any number:'))


if (n==0):
print('the number is zero')
elif (n>0):
print('the number is positive')
else:
print('the number is negative')
Output: Enter any number:-5

the number is negative

5. WAP to find the roots of a quadratic equation

a=int(input('enter the value of a:'))


b=int(input('enter the value of b:'))
c=int(input('enter the value of c:'))
D=(b*b)-(4*a*c)
deno=2*a
if (D>0):
print('Real roots')
root1=(-b+D**0.5)/deno
root2=(-b-D**0.5)/deno
print('root1=',root1, '\t root2=',root2)
elif(D==0):
print('euqal roots')
root1=-b/deno
print('root1 and root2=',root1)

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

6. WAP to print the first 5 numbers

i=0
while (i<=5):
print(i)
i=i+1
Output: 0
1
2
3
4
5

7. WAP to calculate the sum of numbers from m to n

m=int(input('enter the value of m:'))


n=int(input('enter the value of n:'))
s=0
while (m<=n):
s=s+m
m=m+1
print('sum=',s)
Output: enter the value of m:1

69 | P a g e
enter the value of n:10
sum= 55

8. WAP to check a whether a given number is Armstrong or not

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

9. WAP to print the reverse of a 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

reversed number 526

70 | P a g e
FOR LOOP

10. WAP to print numbers from 1 to 5

for i in range (1,6):


print(i)
Output: 1
2
3
4
5

11. WAP to print numbers from 0 to 5

for i in range (6):


print(i)
Output: 0
1
2
3
4
5

12. WAP to print odd numbers from 1 to 10

for i in range (1,10,2):


print(i)
Output: 1
3
5
7
9

71 | P a g e
13. WAP to calculate the average and sum of first n natural numbers

n=int(input('enter the value of n:'))


avg=0
s=0
for i in range (1,n+1):
s=s+i
avg=s/i
print('sum is',s)
print('average is',avg)
Output: enter the value of n:5

sum is 15

average is 3.0

14. WAP to calculate the factorial of a number

n=int(input('enter the number:'))


fact=1
for i in range (1,n+1):
fact=fact*i
print('factorial is',fact)
Output: enter the number:5
factorial is 120

15. WAP to print the Fibonacci series for a given number of terms

n=int(input('enter the no. of terms:'))


first,second=0,1
for i in range (0,n):
if i<=1:
next=i
print(next)

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:

*****
*****
*****
*****
*****

19. WAP to print the following pattern


*
**
***
****
*****
for i in range (5):
for j in range (i+1):
print('*',end=' ')
print()

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:

*****
****
***
**
*

21. WAP to print the following pattern


*
* *
* * *
* * * *
* * * * *
for i in range (5):
for j in range (i,5):
print(' ',end=' ')
for k in range (i+1):
print('*',end=' ')
print()

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:
* * * * *
* * * *
* * *
* *
*

23. WAP to print the following hill pattern


*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
for i in range (5):
for j in range (i,5):
print(' ',end=' ')
for k in range (i):
print('*',end=' ')
for l in range (i+1):
print('*',end=' ')
print()

76 | P a g e
Output:

*
* * *
* * * * *
* * * * * * *
* * * * * * * * *

24. WAP to print the following pattern

* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
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()

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:
*
*
* *
* *
* * *
* * *
* * * *
* * * *
* * * * *
* * *
* * * *
* *
* * *
*
* *
*
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

27. WAP to print the following pattern


5
44
333
2222
11111

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

28. WAP to print the following pattern


1
22
111
2222
11111

79 | P a g e
for i in range (5):

for j in range (i+1):

if(i%2==0):

print('1',end=' ')

else:

print('2',end=' ')

print()

Output:

1
22
111
2222
11111

29. WAP to print the following pattern


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

p=1 #change

for i in range (4):

for j in range (i,5):

print(' ',end=' ')

for k in range (i):

print(p,end=' ') #change

for l in range (i+1):

print(p,end=' ') #change

p=p+1 #change

80 | P a g e
print()

for i in range (5):

for j in range (i+1):

print(' ',end=' ')

for k in range (i,4):

print(p,end=' ') #change

for l in range (i,5):

print(p,end=' ') #change

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

30. WAP to print the following pattern

1
12
123
1234
12345

for i in range (5):


p=1
for j in range (i+1):
print(p,end=' ')
p=p+1
print()

81 | P a g e
Output:

1
12
123
1234
12345

31. WAP to print the following pattern

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

for i in range (5):

p=1

for j in range (i+1):

print(' ',end=' ')

for k in range (i,5):

print(p,end=' ')

p=p+1

print()

Output:

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

32. WAP to print the following pattern


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

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

33. WAP to print the following pattern


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

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()

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

34. WAP to print the following pattern (Floyd Triangle)


1
2 3
4 5 6
7 8 9 10

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

35. WAP to print numbers from 0 to 3 using break

for i in range (0, 30):


print(i)
if i==3:
break
Output: 0
1
2
3

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

37. WAP to demonstrate pass statement


i=1
while i>3:
pass
print('Hello')
Output: Hello

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

2. WAP to detect whether the entered number is prime or composite.


Sol: n=int(input("Enter a no.: "))
if(n == 0 or n == 1):
print("Neither Prime nor Composite")
elif n>1:
for i in range(2, n):
if(n%i==0):
print("Composite no.")
break
else:
print("Prime no.")

86 | P a g e
else:
print("Wrong Input")

Output:
Enter a no.: 7
Prime no.

3. WAP to calculate (xn) using for loop.


Sol: x=int(input("Enter no.: "))
n=int(input("Enter power: "))
k=1
for i in range(1,n+1):
k*=x
print(k)

Output:
Enter no.: 2
Enter power: 4
16

4. WAP to check whether a given year is leap year or not.


Sol: y=int(input("Enter year: "))
if y%4==0:
if y%100!=0 or y%400==0:
print("Leap year")
else:
print("Not a Leap year")

Output:
Enter year: 2004
Leap year

87 | P a g e
𝟏 𝟐 𝒏
5. WAP to find the sum of the series:𝟐 + +∙∙∙∙∙∙∙∙∙∙∙∙∙∙ + 𝒏+𝟏 .
𝟑

Sol: n=int(input("Enter a no.:"))


sum=0
for i in range (1,n+1):
sum+=(i/(i+1))
print(sum)

Output:
Enter a no.:10
7.980122655122655

6. WAP to calculate the sum of cubes of number from 1 to n.


Sol: n=int(input("Enter a no.: "))
sum=0
for i in range (1,n+1):
sum+=(i**3)
print(sum)

Output:
Enter a no.: 10
3025

7. WAP to calculate the sum of squares of number from 1 to n.


Sol: n=int(input("Enter a no.: "))
sum=0
for i in range (1,n+1):
sum+=(i**2)
print(sum)

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

9. WAP to determine whether the character entered is vowel or not.


Sol: c = input("Enter the character: ")
if c.lower() in ('a', 'e', 'i', 'o', 'u'):
print("Vowel")
elif c.upper() in ('A', 'E', 'I', 'O', 'U'):
print("Vowel")
else:
print("Consonant")

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"

n=int(input("Enter a no. (1-7): "))

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

12. WAP to calculate the GCD of two numbers.


Sol: p=int(input("Enter a no.: "))

q=int(input("Enter a no.: "))

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.: "))

print("Countdown begins: ")

while(n>=0):

print(n)

n-=1

91 | P a g e
Output:

Enter a no.: 3

Countdown begins:

2
1
0

14. Print the following patterns.


a) 1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

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

b) for i in range (5):


for j in range (i+1):
print('*',end=' ')
print()
for i in range (4):
for j in range (i,4):
print('*',end=' ')
print()

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

Access of variables in Nested function


The inner function can access variables from both the inner and outer function. Outer
function can access variables only from outer function.
E.g.:
def outer( ):
n_outer = 10
Output:
def inner( ):
m_inner = 11 10

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

Keyword argument with assignment operator


def display(name, age, salary):
print (name)
print (age)
print (salary)
n = „Sara‟
a = 50
s = 12000
display(salary = s, name = n, age = a)

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

4. Variable length argument


def f(name, *subject):
print(name, „likes to read‟)
for sub in subject:
print(sub)
f(„Sara‟, „Maths‟, „Chem‟)
f(„Tara‟, „Eng‟)
f(„Riya‟)
Output:
Sara likes to read Maths Chem
Tara likes to read Eng
Riya likes to read

Lambda/ Anonymous function


It is nameless function defined by lambda keyword
Need for such functions:
1. One time use: Throw away function.
2. Can be used with other higher order functions.
3. Reduces the size of the code.
Syntax: lambda arguments: exp
Key features:
1. It is a nameless function.
2. They can take any number of arguments.
3. They return one value.
4. No return statement
5. Single line function
6. They can‟t access global variables.

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]

j = filter (lambda i: (i>=3), [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)

x = map (lambda y: y+3, [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

s = reduce (lambda x,y: x+y, [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

2. WAP that displays a string repeatedly using function


def func():
for i in range (4):
print('hello')
func()
Output: hello
hello
hello
hello

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

5. WAP to show the use of global statement


def func():
global var
var='hello'
print(var)
func()
print(var)
Output: hello
hello

6. WAP to show the use of same local and global variables


n='Good'
def show():
n='day'
print(n)
print(n)

105 | P a g e
show()
Output: Good
day

7. WAP to show the modification of global variable


var='good'
def func2():
global var
var='day'
print(var)
print(var)
func2()
print(var)
var='book'
print(var)
Output: good
day
day
book

8. WAP to show the modification of local variable


def func2():
var='day'
var='night'
print(var)
func2()
Output: night

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

10. WAP to show access of variables in nested function


def outer():
n_outer=9
def inner():
m_inner=90
print(n_outer)
print(m_inner)
inner()
print(n_outer)
#print(m_inner) #will throw an error
outer()
Output: 9
90
9

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

12. WAP that demonstrates using a variable defined in global namespace


def func():
print(m)
m=70
func()
Output: 70

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

15. WAP to demonstrate keyword arguments


def show2(s,x,y):
print('string is:',s)
print('integer is:',x)
print('float is:',y)
show2(x=9,y=8.9,s='hello')
Output: string is: hello
integer is: 9
float is: 8.9

16. WAP to demonstrate keyword arguments with assignment operator


def details(name,age,salary):
print('name is:',name)
print('age is:',age)
print('salary is:',salary)
n='Sara'
a=50

109 | P a g e
s=12000000
details(salary=s,name=n,age=a)
Output: name is: Sara
age is: 50
salary is: 12000000

17. WAP to show the concept of default argument


def identity(name,age=9):
print('Name is:',name)
print('age is:',age)
identity(name='Sara')
Output: Name is: Sara
age is: 9

18. WAP to show the concept of variable length argument


def fi(name,*subject):
print(name,'likes to read')
for sub in subject:
print(sub)
print(subject)
fi('Sara','Maths','Physics')
fi('Riya','English')
fi('Ajay')
Output: Sara likes to read
Maths
('Maths', 'Physics')
Physics
('Maths', 'Physics')
Riya likes to read

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

20. WAP that uses lambda within a user-defined function


def func(x):
return(lambda y:x+y)
t=func(4)
print(t(8))
Output: 12

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

24. WAP to show the concept of nested lambda function


add=lambda x,y:x+y
mul_add=lambda x,y,z: x*add(y,z)
print(mul_add(3,4,5))
Output: 27

25. WAP that uses lambda function to solve a linear equation


e=lambda x,y:3*x+4*y
e(4,7)
Output: 40

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

29. WAP that uses filter within map function


x=map(lambda x:x+x,filter(lambda x:(x>=5),[3,2,5,6]))
print(list(x))
Output: [10, 12]

30. WAP that uses map within filter function


x=filter(lambda x:(x>=5), map(lambda x:x+x,[2,3,5,6]))
print(tuple(x))
Output: (6, 10, 12)

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

33. WAP to find x^y using recursion


def exp(x,y):
if y==0:
return 1
else:
return x*exp(x,y-1)
x=int(input('enter the value of x:'))
y=int(input('enter the value of y:'))
print('result:',exp(x,y))
Output: enter the value of x:2
enter the value of y:4
result: 16

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']

35. WAP to show the use of from .. import statement


from math import pi
print('pi=',pi)
import math
print('pi=',math.pi)
from math import pi,sqrt
print('pi=',pi)
print(sqrt(4))
Output: pi= 3.141592653589793
pi= 3.141592653589793
pi= 3.141592653589793
2.0

36. WAP to use the concept of as keyword in module


from math import sqrt as square_root
print(square_root(100))
Output: 10.0

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

38. WAP to create user-defined module and import to use it.


def r(x): #(name1.py)
return x*2
def r(x): #(name2.py)
return x**2

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

40. WAP to make a game of ROCK, PAPER and SCISSORS


import random
user_action = input("Enter a choice (rock, paper, scissors): ")
possible_actions = ["rock", "paper", "scissors"]
computer_action = random.choice(possible_actions)
print(f"\nYou chose {user_action}, computer chose {computer_action}.\n")
if user_action == computer_action:
print(f"Both players selected {user_action}. It's a tie!")
elif user_action == "rock":
if computer_action == "scissors":
print("Rock smashes scissors! You win!")
else:
print("Paper covers rock! You lose.")
elif user_action == "paper":
if computer_action == "rock":
print("Paper covers rock! You win!")
else:
print("Scissors cuts paper! You lose.")

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

You chose rock, computer chose rock.

Both players selected rock. It's a tie!

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

2. WAP using function to swap two numbers.


Sol: def swap(a,b):
a=a+b
b=a-b
a=a-b
print("After swap 1st no.: ",a)
print("After swap 2nd no.: ",b)
c=int(input("Enter 1st no.: "))
d=int(input("Enter 2nd no.: "))
swap(c,d)

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

10. WAP using recursive function to print the Fibonacci series.


Sol: def fibonacci(x):
if x<=1:
return x
else:
return (fibonacci(x-1)+fibonacci(x-2))
n=int(input("Enter no. of terms: "))
print("Fibonacci series: ")
for i in range(n):
print(fibonacci(i), end=' ')

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

12. WAP that generates 10 random numbers between 1 to 100.


Sol: import random
for i in range(10):
print(random.randint(1,100),end=' ')

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

You might also like