0% found this document useful (0 votes)
12 views54 pages

Python Lab Manual

The document is a lab manual for the Python Programming Laboratory course (CS206ES) for the academic year 2023-2024 at ACE Engineering College. It outlines the department's vision and mission, course objectives, outcomes, a list of experiments, and evaluation schemes. The manual serves as a comprehensive guide for students to learn Python programming and its applications in data science and artificial intelligence.

Uploaded by

monika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views54 pages

Python Lab Manual

The document is a lab manual for the Python Programming Laboratory course (CS206ES) for the academic year 2023-2024 at ACE Engineering College. It outlines the department's vision and mission, course objectives, outcomes, a list of experiments, and evaluation schemes. The manual serves as a comprehensive guide for students to learn Python programming and its applications in data science and artificial intelligence.

Uploaded by

monika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Lab Manual

For
PYTHON PROGRAMMING LABORATORY
[CS206ES]

Academic Year: 2023-2024

I B. TECH II SEMESTER (JNTUH R22)

DEPARTMENT OF CSE(Artificial Intelligence and Machine Learning)

ACE
Engineering College
An Autonomous Institution
Ghatkesar, Hyderabad - 501 301,
Telangana. Approved by AICTE &
Affiliated to JNTUH
NBA Accredited [Link] Courses, Accorded NACC A-Grade with
3.20 CGPA

1
INDEX

[Link] Contents Page No.

1 Department Vision, Mission, POs and 1


PSOs
2 Objectives and Course Outcomes of the 3
lab
3 Requirements 3

4 List of Experiments 4

5 Module Wise Outcomes 5

6 COs Mapping with POs and PSOs 5

7 Introduction to Lab 7

8 Lab Experiments 16

9 Additional experiments- beyond syllabus 40

10 Scheme of Evaluation 43

11 References 44

2
Institute Vision:

To be a leading Technical Institute to prepare high quality Engineers to cater the needs
of the stakeholders in the field of Engineering and Technology with global competence
fundamental comprehensive analytical skills, critical reasoning, research aptitude,
entrepreneur skills, ethical values and social concern.

Institute Mission:
Imparting Quality Technical Education to young Engineers by providing the state-of-
the-art laboratories, quality instructions by qualified and experienced faculty and
research facilities to meet the requirements of stakeholders in real time usage and in
training them to excel in competitive examinations for higher education and employment
to interface globally emerging techno-informative challenges in the growth corridor of
techno-excellence.

Department Vision:
To produce excellent standard, quality education of professionals by imparting cognitive
learning environment, research and industrial orientation to become innovative Data
Science Professional.
Department Mission:

M1. To develop professionals in the areas of math‟s (probability and statistics,


liner algebra and Calculus), natural language processing, text mining, and problem
solving.

M2 . To educate the students with latest technologies to update their knowledge in


the field of AI and Data science.

M3. To impart quality and value based education and contribute towards the
innovation of computing system, data science to raise satisfaction level of all
stakeholders
M4. Enabling students to get expertise in critical skills with data science education
and facilitate socially responsive research and innovation.
M5. Our effort is to apply new advancements in high performance computing
hardware and software

3
Program Out comes (POs)

Program Statements
Outcome
s
Analyze and build models applying the knowledge of mathematics, statistics,
PO1
electronic, electrical and computer science discipline and solve the problem.
Identify the sources of information for data collection, design and conduct
PO2 the experiments and interpret the result.

Think out-of-the box and solve the real time problems using their creativity
PO3 in designing human friendly software systems.

Comprehend computer engineering concepts of the new research


PO4 developments and apply them to develop relevant software and hardware
products.
Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
Apply the computing knowledge to solve the socially relevant problems.
PO6

Understand the impact of engineering solutions in global, economic,


PO7
environmental, societal context and apply it in exploring the new
developments research trends and involve them in research.
Develop professional integrity by understanding and appreciating
PO8 professional ,legal, ethical, cyber security and related issues and act with
responsibility.
Communicate, collaborate and work as a team by involving in the group
PO9
projects of multi-disciplinary nature.
4
To prepare documents as per the standards and present effectively to
PO10
improve software documentation skills.

PO11 Apply the hardware and software project management techniques to estimate
the time and human resources required to complete computer engineering
projects.

Recognize the need for, and have the preparation and ability to
PO12
engage in independent and life-long learning in the broadest context
of technological change

5
Program Specific Outcomes (PSOs)

Program Statement
Specific
Outcomes
PSO1 Understand, analyze and develop essential proficiency in the areas related to
data science in terms of underlying statistical and computational principles and
apply the knowledge to solve practical problems.
PSO2 Implement data science techniques such as search algorithms, neural networks,
machine learning and data analytics for solving a problem and designing novel
algorithms for successful career and entrepreneurship

6
Course Objectives:

[Link] Course Objectives


1 To install and run the Python interpreter
2 To learn control structures.
3 To Understand Lists, Dictionaries in python
4 To Handle Strings and Files in Python

1 Ability to Develop the application specific codes using python.


2 Ability to Understand Strings, Lists, Tuples and Dictionaries in Python
3 Ability to Verify programs using modular approach, file I/O, Python
standard library
4 Ability to Implement Digital Systems using Python

Course Outcomes:

Hardware Requirements:

 Processor: Inteli3orhigher
 RAM: 4GB
 Memory:500GB

Software Requirements:
 Python3

7
8
List of Experiments:

[Link] Program Name

a) i) Use a web browser to go to the Python website [Link]


This page contains information about Python and links to Python-related
pages, and it gives you the ability to search the Python documentation.
ii) Start the Python interpreter and type help () to start the online help
1 utility.
b) Start a Python interpreter and use it as a Calculator.
c)i) Write a program to calculate compound interest when principal, rate
and number of periods are given.
ii) Given coordinates (x1, y1), (x2, y2) find the distance between two
point
d)Read name, address, email and phone number of a person through
keyboard and print the details.

a) Print the below triangle using for loop.


5
44
333
2 2222
11111
b) Write a program to check whether the given input is digit or lowercase
character or uppercase character or a special character (use 'if-else-if'
ladder)

9
c) Python Program to Print the Fibonacci sequence using while loop
d) Python program to print all prime numbers in a given interval (use
break)

a)i) Write a program to convert a list and tuple into arrays.


ii) Write a program to find common values between two arrays.
3 b) Write a function called gcd that takes parameters a and b and returns
their greatest common divisor.
c) Write a function called palindrome that takes a string argument and
returns T rue if it is a palindrome and False otherwise. Remember that you
can use the built-in function len to check the length of a string.
a) Write a function called is sorted that takes a list as a parameter and
returns True if the list is sorted in ascending order and False otherwise.
b) Write a function called has_duplicates that takes a list and returns True
if there is any element that appears more than once. It should not modify
the original list.
i). Write a function called remove_duplicates that takes a list and returns a
4 new list with only the unique elements from the original. Hint: they don’t
have to be in the same order.
ii). The wordlist I provided, [Link], doesn’t contain single letter words.
So you might want to add“I”, “a”, and the empty string.
iii). Write a python code to read dictionary values from the user. Construct
a function to invert its content. i.e., keys should be values and values
should be keys.
c) i) Add a comma between the characters. If the given word is 'Apple', it
should become 'A,p,p,l,e'
ii) Remove the given word in all the places in a string?
iii) Write a function that takes a sentence as an input parameter and
replaces the first letter of every word with the corresponding upper case
10
letter and the rest of the letters in the word by corresponding letters in
lower case without using a built-in function?
d) Writes a recursive function that generates all binary strings of n-bit
length

a) i) Write a python program that defines a matrix and prints


ii) Write a python program to perform addition of two square matrices
5 iii) Write a python program to perform multiplication of two square
matrices
b) How do you make a module? Give an example of construction of a
module using different geometrical shapes and operations on them as its
functions.
c) Use the structure of exception handling all general purpose exceptions.

a) i) Write a function called draw_rectangle that takes a Canvas and a


Rectangle as arguments anddraws a representation of the Rectangle on the
Canvas.
ii) Add an attribute named color to your Rectangle objects and modify
6 draw_rectangle so that ituses the color attribute as the fill color.
iii) Write a function called draw_point that takes a Canvas and a Point as
arguments and draws arepresentation of the Point on the Canvas.
iv) Define a new class called Circle with appropriate attributes and
instantiate a few Circle [Link] a function called draw_circle that
draws circles on the canvas.
b) Write a Python program to demonstrate the usage of Method
Resolution Order (MRO) in multiplelevels of Inheritances.
c) Write a python code to read a phone number and email-id from the user
and validate it forcorrectness.
a) Write a Python code to merge two given file contents into a third file.
b) Write a Python code to open a given file and construct a function to
11
check for given words present init and display on found.
7 c) Write a Python code to Read text from a text file, find the word with
most number of occurrences
d) Write a function that reads a file file1 and displays the number of
words, number of vowels, blankspaces, lower case letters and uppercase
letters.

i)Import numpy, Plotpy and Scipy and explore their functionalities.


ii)InstallNumPy package with pip and explore it.
8 iii) Write a program to implement Digital Logic Gates – AND, OR, NOT,
EX-OR
iv) Write a program to implement Half Adder, Full Adder, and Parallel
Adder
v)Write a GUI program to create a window wizard having two text labels,
two text fields and two buttonsas Submit and Reset.

12
Module wise Outcome:

[Link] Program Name Course Outcome


1 Use a web browser to go to Ability to Develop the application specific
the Python website and The codes using python.
Python interpreter
Python Program to Print the Ability to Verify programs using modular
2 Fibonacci sequence, Prime approach, file I/O, Python standard library
Numbers and special
Character
A function called gcd , Ability to Verify programs using modular
3 palindrome and find common approach, file I/O, Python standard library
values between two arrays.
4 Functions Ability to Understand Strings, Lists, Tuples
and Dictionaries in Python
5 Structure of Exception Ability to Understand Strings, Lists, Tuples
handling and Dictionaries in Python
6 Draw the shapes using Ability to Implement Digital Systems using
different functions Python
7 Files Ability to Develop the application specific
codes using python.
8 Numpy Ability to Understand Strings, Lists, Tuples
and Dictionaries in Python

13
Cos Mapping with Pos and PSOs:

Program PS
Outcome(POs) Os
CO P PO PO PO PO P PO PO PO PO PO PO PS PS PS BT
O1 2 3 4 5 O 7 8 9 10 11 12 O O O L
6 1 2 3
C 3 3 3 3 3 2 1 2,3
O ,6
1
C 3 3 3 3 3 3 3,6
O
2
C 2 3 3 2 3 3 3
O
3
C 3 3 3 3 3 3 3 3,6
O
4
C 1 3 1 3 3 2 2 2 1 3 3 3
O
5
C 3 3 3 3 2 2 2 3 3 3 2 3 3
O
6
2.3 3.0 2.3 2.8 3.0 2.0 2.0 2.0 2.5 2.8 3.0 2.7 2.3
INTRODUCTIONTOLAB:
History :

14
 Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.

 Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
Small Talk ,Unix shell, and other scripting languages.

 Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).

 python first version is 1.0 and latest version is 3.7

 The logo of python shows two intertwined snakes

 Major implementations of Python are Cpython, Iron Python, Jpython, MicroPython, PyPy

 Top software companies like Google , Microsoft ,IBM , Yahoo using python

Features
 Simple & Easy to Learn

 Free and Open Source

 High Level Language

 Platform Independent Language

 Dynamically Typed Language

 Procedure oriented and Object oriented

 Interpreted

 Portable, Extendable

 Embedded

 Extensive Standard Library

15
 Databases and GUI Programming

 Automatic Garbage Collection

A simple language which is easier to learn


Python has a very simple and elegant syntax. It's much easier to read and write when compared
to other languages like: C++, Java, C#.
Free and open-source
You can freely use and distribute Python, even for commercial use. Not only can you use and
distribute software's written in it, you can even make changes to the Python's source code.
High level language
High level languages use English words to develop programs. These are easy to learn and use.
Like C, Java and PHP, Python also uses English words in its program
Platform Independent
It is platform independent programming language, its code easily run on any platform such as
Windows, Linux, Unix , Macintosh etc. A Python program written on a Macintosh computer
will run on a Linux system and vice versa
Dynamically typed language
In python there is no need to declare the type of a [Link] we assign a value to the
variable, based on the value the type will be allocated automatically.
Object-oriented
A programming language that can model the real world is said to be object-oriented.
Everything in Python is an object. Object oriented programming (OOP) helps you solve a
complex problem very easily With OOP, you are able to divide these complex problems into
smaller sets by creating objects.
A high-level, interpreted language
interpreter executes the code line by line at a time. Unlike C/C++, you don't have to worry
about difficult tasks like memory management, garbage collection and so on. Likewise, when
16
you run Python code, it automatically converts your code to the language your computer
understands. You don't need to worry about any lower-level operations.
Portability
You can move Python programs from one platform to another, and run it without any changes.
It runs seamlessly on almost all platforms including Windows, Mac OS X and Linux.
Extensible
Suppose an application requires high performance. You can easily combine pieces of C/C++ or
other languages with Python code. This will give your application high performance as well as
scripting capabilities which other languages may not provide out of the box.
Embeddable
We can embed the python code into other languages such as C, C++, Java, Etc..To provide the
scripting capabilities to other languages we can use the python code in it.
Extensive Standard Library
Python has a number of standard libraries which makes life of a programmer much easier since
you don't have to write all the code yourself. Developers can use the built-in libraries for their
applications. By making use of these built-in libraries, development will become faster.
Databases and GUI Programming
Python provides interfaces to connect its programs to all major databases like Oracle, Sybase or
Mysql. We can develop GUI based applications and Web applications using Python Language
Applications of Python:
 Automation Applications

 Data Analytics & Visualization

 Scientific Applications

 Web Applications

 Web Scrapping

17
 Administration Script

 Networking with IOT Applications

 Test Cases

 GUI Applications

 Gaming Applications

 Animation Applications

Installation and Setting up path

To install Python on a Windows machine, follow these steps:

1. Open a web browser and go to [Link]


2. Click the Downloads.
3. Click the python 3.7.3 link to download the installer file.

4. Store the Windows Installer file somewhere on your computer, such as C:\download\ python
[Link] (Just create a directory where you can find it later.)

5. Run the downloaded file by double-clicking it in Windows Explorer. Just accept the default
settings, wait until the installation is finished, and you’re ready to roll!

 Run the Python Integrated Development Environment (IDLE) by selecting Start


➤Programs ➤ Python3 ➤ IDLE (Python GUI).

18
Working with Python Basic Syntax

There are two ways to use the Python interpreter:

1. Interactive Mode / shell mode (line by line execution)


In shell mode, you type Python expressions into the Python shell, and the interpreter
immediately shows the result.

>>> 2 + 3

>>>

The >>> is called the Python prompt.

2. Batch Mode (entire program execution at a time)


The concept of writing group of python statements into a file,
saving that file with the extension ‘.py’ and submitting the entire file to the python
interpreter at a time is known as Batch mode.

19
Data types
Every value in Python has a data type. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes. There are
various data types in Python. Some of the important types are listed below.
 None : Nothing or no value associated
 Numbers
 List
 Tuple
 String
 Set
 Dictionary

Numbers:
Number stores numeric values. Python creates Number objects when a number is assigned to a
variable
Ex: a,b=4,5 # a and b are objects
There are 3 sub types
 int : The int data type represents an integer number( 200)
 float: The float data type represents floating point number(3.14)
 complex: A complex number is a number that is written in the form of a+bj or a+bJ(3.14j,
2-3.5J)
bool: It is used to represent Boolean values(True and False)
Lists:
Lists in python are similar to arrays in C. However the list can contain data of different types.
The items stored in the list are separated with a comma (,) and enclosed within square brackets
[].We can use slice [:] operators to access the data of the list.
l = [1, "hi", "python", 2]
print (l[2:])
print (l[0:2])
20
Tuple:

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The elements in the tuple are separated with a comma (,) and
enclosed in parentheses ().Whereas the list elements can be modified, it is not possible to
modify the tuple elements
t = (10,5.3,"hi", "python", 2)
print (t[1:]);
print (t[0:1]);
t[3]=77 #Error

String :
A string is represented by group of characters represented in quotation marks. In python,
strings are enclosed in single or double quotes. Multi-line strings can be denoted using triple
quotes, ''' or """. slicing operator [ :] can be used to retrieve parts of string
s=‘hello’
str2=“welcome “
str3 =“ “ “ python ” ” ”
print(s[-4])
print(s[2:])

Dictionary:
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a
huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to
retrieve the value. In Python, dictionaries are defined within braces {} with each item being a
pair in the form key: value. Key and value can be of any type.
d = {1:'value','key':2}
print(d[1])
print(d[‘key’]

Range:
The range data type represents a sequence of numbers. The numbers in the range are not
modifiable. Generally range is used for repeating a for loop for specific number of times. To
create a range of numbers, we can simply write
r=range(10) r=range(2,9)

r=range(1,10,2)

Set:
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered. it means the elements may not appear in the
21
same order as they are entered into the sets
a = {5,2,3,1,4}
print(a)

Type conversion:

The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion. It is done by using different type conversion functions like int(),
float(), complex and str() etc.

int():This function converts any data type to integer except complex type
>>>int(23.45) #23
>>>int(“44”) #44
>>>int(True) #1

float():This function is used to convert any data type to a floating point number except complex
type
>>>float(5) #5.0
>>>float(“10.5”) #10.5
>>>float(“10”) #10.0
>>>float(True) #1
Complex(): This function convert other types to complex type
>>>complex(10) #10+0j
>>>complex(False) #0j
>>>complex(“10.5”) #10.5+0j
str(): This function convert other type values to str type
>>>str(10) #’10’
>>>str(True) #’True’

Python Variables
A variable is a location in memory used to store some data(value). The rules for writing a
variable name is same as the rules for writing identifiers in Python. We don't need to declare a
variable before using it. In Python, we simply assign a value to a variable and it will exist.
We don't even have to declare the type of the variable. This is handled internally according to
the type of value we assign to the variable.
Variable assignment
We use the assignment operator (=) to assign values to a variable. Any type of value can be
22
assigned to any valid variable.
Ex: a=5 a=b=c=1
b = 3.2
c = "Hello“
Changing the value of a variable
Ex: a=4
print(a)
a=“hello”
print(a)
Assigning multiple values to multiple variables
Ex: name ,rno , avg = “Hello”, 15, 95.3
Note: Every Variable in Python is a Object

23
Python Indentation :
 Most of the programming languages like C, C++, Java use braces { } to define a block
of code .

 But Python provides no braces{} to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation

 Whitespace is used for indentation in Python

 The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount.

 A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent
throughout that block. If a block has to be more deeply nested, it is simply indented
further to the right.

fori in range(1,11):
print(i)
ifi == 5:
break
1. a) i) Use a web browser to go to the Python website [Link] This
page contains information about Python and links to Python-related pages,
and it gives you the ability to search the Python documentation.

Output:

ii) Start the Python interpreter and type help() to start the online help utility
Output:

b) Start a Python interpreter and use it as a Calculator


Output:

c) i) Write a program to calculate compound interest when principal, rate and


number of periods are given
Source Code:
defcompound_interest(principal, rate, time):
# Calculates compound interest
Amount = principal * (pow((1 + rate / 100), time))
CI = Amount - principal
print("Compound interest is", CI)
# Driver Code
compound_interest(10000, 10.25, 5)
Output:
Compound interest is 6288.946267774416
ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points
Source Code:
import math
p1 = [4, 0]
p2 = [6, 6]
distance = [Link]( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )

print(distance)
Output:
6.324555320336759

d) Read name, address, email and phone number of a person through keyboard and
print the details.
Source Code:

print("Enter your name: ", end="")


name = input()

print("Enter your Phonenumber: ", end="")


Phonenumber = input()

print("Enter your email: ", end="")


email = input()

print("Enter your address: ", end="")


Address = input()

print("Name: ", name)


print("Contact:", Phonenumber)
print("Email: ", email)
print("Address: ", Address)
Output:
Enter your name: ACE
Enter your Phonenumber: 123456789
Enter your email: abc@[Link]
Enter your address: Hyderabad
Name: ACE
Contact: 123456789
Email: abc@[Link]
Address: Hyderabad
2)a) Print the below triangle using for loop.
5
44
333
2222
11111
Source Code:
row = 5
a=0
fori in range(row, 0, 1):
a += 1
for j in range(1, i + 1):
print(a, end=' ')
print('\r')
Output:
5
44
333
2222
11111
b) Write a program to check whether the given input is digit or lowercase character
or uppercase character or a special character (use 'if-else-if' ladder)
SourceCode:
ch = input("Enter a character: ")
ifch>= '0' and ch<= '9':
print("Digit")
[Link] ():
print("Uppercase character")
[Link] ():
print("Lowercase character")
else:
print("Special character")
Output:
Enter a character: a
Lowercase character

Enter a character: A
Uppercase character

Enter a character: 1
Digit
c) Python Program to Print the Fibonacci sequence using while loop
Source Code:
n = int(input("Enter the value of 'n': "))
a=0
b=1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a=b
b = sum
sum = a + b
Output:
Enter the value of 'n': 5
Fibonacci Series: 0 1 1 2 3

d) Python program to print all prime numbers in a given interval (use break)
Source Code:
lower = 100
upper = 200
print("Prime numbers between", lower, "and", upper, "are:")
fornum in range(lower, upper + 1):
# all prime numbers are greater than 1
ifnum> 1:
fori in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Output:
Prime numbers between 100 and 200 are:
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
3.a)i)Write a program to convert a list and tuple into arrays.
Source Code:
importnumpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 8]
print("List to array: ")
print([Link](my_list))
my_tuple = ([8, 4, 6], [1, 2, 3])
print("Tuple to array: ")
print([Link](my_tuple))
Output:
List to array:
[1 2 3 4 5 6 7 8]
Tuple to array:
[[8 4 6]
[1 2 3]]

ii) Write a program to find common values between two arrays.


Source Code:
importnumpy as np
array1 = [Link]([0, 10, 20, 40, 60])
print("Array1: ",array1)
array2 = [10, 30, 40]
print("Array2: ",array2)
print("Common values between two arrays:")
print(np.intersect1d(array1, array2))
Output:
Array1: [ 0 10 20 40 60]
Array2: [10, 30, 40]
Common values between two arrays:
[10 40]
b) Write a function called gcd that takes parameters a and b and returns their
greatest common divisor.
Source Code:
defcomputeGCD(x, y):
if x > y:
small = y
else:
small = x
fori in range(1, small + 1):
if((x % i == 0) and (y % i == 0)):
gcd = i
returngcd
a = 60
b = 48
print ("The gcd of 60 and 48 is : ", end="")
print (computeGCD(60,48))
Output:
The gcd of 60 and 48 is : 12
c) Write a function called palindrome that takes a string argument and returnsTrue
if it is a palindromeand False otherwise. Remember that you can use the built-in
function len to check the length of a string
Source Code:
def palindrome(string):
length = len(string)
first = 0
last = length -1
status = 1
while(first<last):
if(string[first]==string[last]):
first=first+1
last=last-1
else:
status = 0
break
returnint(status)
string = input("Enter the string: ")
status= palindrome(string)
if(status):
print("True ")
else:
print("False")
Output:
Enter the string: madam
True
4.a) Write a function called is_sorted that takes a list as a parameter and returns
True if the list is sortedin ascending order and False otherwise.
Source Code:
defis_sorted():
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]
#sort list in-place in ascending order
my_numbers.sort()
#print modified list
print("my_numbers are sorted",my_numbers)
is_sorted()
Output:
my_numbers are sorted [3, 7, 8, 10, 11, 22, 33, 54, 100]

b) Writes a recursive function that generates all binary strings of n-bit length
SourceCode:
defprintTheArray(arr, n):
fori in range(0, n):
print(arr[i], end = " ")
print()
# Function to generate all binary strings
defgenerateAllBinaryStrings(n, arr, i):
ifi == n:
printTheArray(arr, n)
return
arr[i] = 0
generateAllBinaryStrings(n, arr, i + 1)
arr[i] = 1
generateAllBinaryStrings(n, arr, i + 1)
if __name__ == "__main__":
n=4
arr = [None] * n
generateAllBinaryStrings(n, arr, 0)
Output:
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
c) Write a python code to read dictionary values from the user. Construct a function
to invert its content. i.e., keys should be values and values should be keys

Source Code:
old_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69, 'G': 67, 'H': 23}

new_dict = dict([(value, key) for key, value in old_dict.items()])

# Printing original dictionary


print ("Original dictionary is : ")
print(old_dict)

print()

# Printing new dictionary after swapping keys and values


print ("Dictionary after swapping is : ")
print("keys: values")
fori in new_dict:
print(i, " : ", new_dict[i])
Output:
Original dictionary is :
{'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69, 'G': 67, 'H': 23}

Dictionary after swapping is :


keys: values
67 : G
23 : H
45 : C
56 : D
12 : E
69 : F
5.a) Write a python program that defines a matrix and prints
Source Code:
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))

# Initialize matrix
matrix = []
print("Enter the entries rowwise:")

# For user input


fori in range(R): # A for loop for row entries
a =[]
for j in range(C): # A for loop for column entries
[Link](int(input()))
[Link](a)

# For printing the matrix


fori in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()
Output:
Enter the number of rows:2
Enter the number of columns:3
Enter the entries rowwise:
1
2
4
124
124
b) Use the structure of exception handling all general purpose exceptions.
Source Code:
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])

exceptZeroDivisionError:
print("Denominator cannot be 0.")

exceptIndexError:
print("Index Out of Bound.")

Output: Index Out of Bound

6) Write a function called draw rectangle that takes a Canvas and a Rectangle as
arguments anddraws a representation of the Rectangle on the Canvas.
Source Code:
importtkinter as tk
master = [Link]()
def rectangle(event):
w.create_rectangle(event.x, event.y, event.x + 10, event.y + 10, fill="blue")
w = [Link](master, width=200, height=200)
[Link]()
[Link]("&lt;Button-1&gt;", rectangle)
[Link]()
Output:
b)Write a Python program to demonstrate the usage of Method Resolution Order
(MRO) in multiple levels of Inheritances.
Source Code:
class A:
defrk(self):
print(" In class A")
class B(A):
defrk(self):
print(" In class B")
class C(A):
defrk(self):
print("In class C")

# classes ordering
class D(B, C):
pass

r = D()
[Link]()

Output:

In class B
7.a) Write a Python code to merge two given file contents into a third file
# Open the first file for reading
open('[Link]', 'r') as file1:
# Read the contents of file1
file1_contents = [Link]()

# Open the second file for reading


open('[Link]', 'r') as file2:
# Read the contents of file2
file2_contents = [Link]()

# Open the third file for writing


open('[Link]', 'w') as file3:
# Write the contents of file1 followed by the contents of file2
[Link](file1_contents + file2_contents)
b) Write a Python code to open a given file and construct a function to check for
given words present in it and display on found
def check_words_in_file(filename, words):
with open(filename, 'r') as file:
file_content = [Link]()
for word in words:
if word in file_content:
print(f"'{word}' is present in '{filename}'")
c)Write a Python code to Read text from a text file, find the word with most number
of occurrences
def find_most_common_word(filename):
with open(filename, 'r') as file:
word_count = {}
for line in file:
words = [Link]().split()
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
most_common_word = max(word_count, key=word_count.get)
print(f"The most common word is '{most_common_word}' with
word_count[most_common_word]} occurrences.")
d) Write a function that reads a file file1 and displays the number of words, number of
vowels, blank spaces, lower case letters and uppercase letters
def analyze_file(file_name):
with open(file_name, 'r') as file:
content = [Link]()
word_count = len([Link]())
vowel_count = 0
uppercase_count = 0
lowercase_count = 0
space_count = 0
for char in content:
if [Link]():
uppercase_count += 1
elif [Link]():
lowercase_count += 1
elif char == ' ':
space_count += 1
if [Link]() in ['a', 'e', 'i', 'o', 'u']:
vowel_count += 1
print(f"Number of words: {word_count}")
print(f"Number of vowels: {vowel_count}")
print(f"Number of blank spaces: {space_count}")
print(f"Number of lowercase letters: {lowercase_count}")
print(f"Number of uppercase letters: {uppercase_count}")

Output:
Enter the file name 1: Pyhton
['Computer science Engineering\n', 'Elecronics and Communication
Engineering\n', 'Civil Engineering\n']
Enter the file name 2: c++
Computer science Engineering
Elecronics and Communication
EngineeringCivil Engineering

8.a) Import numpy, Plotpy and Scipy and explore their functionalities.
Source Code:
fromscipy import special #same for other modules
importnumpy as np

importnumpy as np
fromscipy import io as sio
array = [Link]((4, 4))
[Link]('[Link]', {'ar': array})
data = [Link](‘[Link]', struct_as_record=True)
data['ar']
Output:
array([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]])
Source Code:
[Link] import cbrt
#Find cubic root of 27 & 64 using cbrt() function
cb = cbrt([27, 64])
#print value of cb
print(cb)
Output: array ([3., 4.])

Source Code:
[Link] import comb
#find combinations of 5, 2 values using comb(N, k)
com = comb(5, 2, exact = False, repetition=True)
print(com)
Output:
15.0
c) Write a program to implement Digital Logic Gates – AND, OR, NOT,
EX-OR

Source Code:

def AND (a, b):

if a == 1 and b == 1:
return True
else:
return False

# Driver code
if __name__=='__main__':
print(AND(1, 1))

print("+---------------+----------------+")
print(" | AND Truth Table | Result |")
print(" A = False, B = False | A AND B =",AND(False,False)," | ")
print(" A = False, B = True | A AND B =",AND(False,True)," | ")
print(" A = True, B = False | A AND B =",AND(True,False)," | ")
print(" A = True, B = True | A AND B =",AND(True,True)," | ")
Output:
True

+---------------+----------------

| AND Truth Table | Result |

A = False, B = False | A AND B = False |


A = False, B = True | A AND B = False |

A = True, B = False | A AND B = False |

A = True, B = True | A AND B = True |

def NAND (a, b):


if a == 1 and b == 1:
return False
else:
return True
Source Code:
if __name__=='__main__':
print(NAND(1, 0))

print("+---------------+----------------+")
print(" | NAND Truth Table | Result |")
print(" A = False, B = False | A AND B =",NAND(False,False)," | ")
print(" A = False, B = True | A AND B =",NAND(False,True)," | ")
print(" A = True, B = False | A AND B =",NAND(True,False)," | ")
print(" A = True, B = True | A AND B =",NAND(True,True)," | ")
Output:
True
+---------------+----------------+
| NAND Truth Table | Result |
A = False, B = False | A AND B = True |
A = False, B = True | A AND B = True |
A = True, B = False | A AND B = True |
A = True, B = True | A AND B = False |
Source Code:
def OR(a, b):
if a == 1 or b ==1:
return True
else:
return False

# Driver code
if __name__=='__main__':
print(OR(0, 0))

print("+---------------+----------------+")
print(" | OR Truth Table | Result |")
print(" A = False, B = False | A OR B =",OR(False,False)," | ")
print(" A = False, B = True | A OR B =",OR(False,True)," | ")
print(" A = True, B = False | A OR B =",OR(True,False)," | ")
print(" A = True, B = True | A OR B =",OR(True,True)," | ")
Output:
False

+---------------+----------------+

| OR Truth Table | Result |

A = False, B = False | A OR B = False |

A = False, B = True | A OR B = True |

A = True, B = False | A OR B = True |

A = True, B = True | A OR B = True |

d) Write a GUI program to create a window wizard having two text labels,
two text fields and two buttonsas Submit and Reset

Source Code:

importtkinterastk

defwrite_text():

print("Tkinter is easy to create GUI!")

parent=[Link]()

frame=[Link](parent)

[Link]()

text_disp=[Link](frame,

text="Hello",

command=write_text

text_disp.pack(side=[Link])
exit_button=[Link](frame,

text="Exit",

fg="green",

command=quit)

exit_button.pack(side=[Link])

[Link]()
Output:

AdditionalExperiments-beyondsyllabus:

Experiment-1:
DescribeaboutInstancevariableusingATMMachineClassProgram:

SOURCECODE:

classATM:

definit(self):
[Link]=0 #instanceVariableprint
"NewAccount Created"

defdeposit(self):
amount=input("Entertheamounttodeposit:"
)[Link]=[Link]+amount

print"NewBalanceis",[Link](self):a
mount=input("Enterthe amountto withdraw:")
[Link]<amount:

print"InsufficientBalance"else:
[Link]=[Link]-amount

print"NewBalanceis",[Link]
y(self):

print"TheBalanceis",[Link]=
ATM()

[Link]()

[Link]()

Output

NewAccountCreated

Entertheamountto deposit:1200
NewBalanceis1200Enter the amount
to withdraw: 950 New Balance is
250Enter the amounttowithdraw:120
Experiment-2:

DescribeaboutClassvariableusingRobotClass Program:

SOURCECODE:

classRobot:

what="Machine" #class
Variablename="Chitti"

version=1.0spee="1T
Hz"
memory="1ZB"
defupdate(cls):[Link]=2.0
[Link]="2THz"[Link]=
"2ZB"
r=Robot()

print "Haii am a",[Link] print


"MyName is",[Link]
print"Version",[Link]
print"Speed",[Link]
print"Memory",[Link]()

print""
print "Haii am a",[Link]
print"My Name is",[Link]
print"Version",[Link]
print"Speed",[Link]
print"Memory",[Link]

Output:
Haii am a
MachineMyName
isChitti

Version 1.0
Speed1THz
Memory1ZB

Haii am a
MachineMyNameis
Chitti

Version 2.0
Speed2THz

Memory2ZB

SchemeofEvaluation:
InternalAssessment

[Link]. Assessment of work Evaluation in


Marks
1 Lab observation-day today 10
work
10
2 Record
10
3 Viva
10
4 Internal laboratory Test
Total 40
Marks

External Assessment
[Link]. Assessment of Evaluation in Marks
work
1 Writeup 20
2 Experimentation 20
3 Observation 10
4 Viva 10

Total 60
Marks

Reference Books:

TEXTBOOKS:

1. Supercharged Python: Take your code to the next level, Overland

2. Learning Python, Mark Lutz, O'reilly

REFERENCEBOOKS:

1. Python Programming: A Modern Approach, Vamsi Kurama, Pearson

2. 2. Python Programming A Modular Approach with Graphics, Database,

Mobile, and Web Applications, Sheeta lTaneja, Naveen Kumar,


Pearson
3. 3. Programming with Python, A User’s Book, Michael Dawson,

Cengage Learning, India Edition


4. 4. Think Python, Allen Downey, Green Tea Press
5. 5. Core Python Programming, W. Chun, Pearson 6. Introduction to

Python, Kenneth A. Lambert, Cengage.

You might also like