Python File
Python File
(CIE – 332P)
VISION
To attain global excellence through education, innovation, research, and work ethics with the
commitment to serve humanity.
MISSION
M2. To foster moral values in students and equip them for developing sustainable solutions to
serve both national and global needs in society and industry.
M3. To digitize educational resources and process for enhanced teaching and effective
learning.
VISION
MISSION
M1: To excel in the field by imparting quality education and skills for software development
and applications.
M2: To establish a conducive environment that promotes intellectual growth and research.
M3: To facilitate students to acquire entrepreneurial skills for innovation and product
development.
M4: To encourage students to participate in competitive events and industry interaction with a
focus on continuous learning.
Programming Python Lab CO’s and its mapping with
PO’s and PSO’s
Program Specific Outcomes (PSOs)
PSO1: Students are equipped with programming technologies applied in the industry.
PSO2: Students are able to provide efficient solutions for emerging challenges in the
computation domain such as Artificial Intelligence, Data Science, Web Technologies.
PSO3: Students are able to apply domain knowledge and expertise in the field of Information
Technology for enhancing research capability to transform innovative ideas into reality.
Course Objectives :
1. Learn the syntax and semantics of Python Programming Language.
2. Write Python functions to facilitate code reuse and manipulate strings.
3. Illustrate the process of structuring the data using lists, tuples and dictionaries.
4. Demonstrate the use of built-in functions to navigate the file system.
Course Outcomes (CO)
CO 1 Demonstrate the concepts of control structures in Python.
CO 2 Implement Python programs using functions and strings.
CO 3 Implement methods to create and manipulate lists, tuples and dictionaries
CO 4 Apply the concepts of file handling and regExusing packages.
Course Outcomes (CO) to Programme Outcomes (PO) mapping (scale 1: low, 2: Medium, 3: High)
PO01 PO02 PO03 PO04 PO05 PO06 PO07 PO08 PO09 PO10 PO11 PO12
CO 1 3 2 2 2 3 - - - 3 2 2 3
CO 2 3 2 2 2 3 - - - 3 2 2 3
CO 3 3 2 2 2 3 - - - 3 2 2 3
CO 4 3 2 2 2 3 - - - 3 2 2 3
CO-PSO Mapping
PRACTICAL RECORD
PRACTICAL DETAILS
AIM: Basic data types and operators: Create a program that prompts the user for their
name and age and prints a personalized message.
THEORY: For this experiment, we'll be working with basic data types (strings and integers)
and operators (input, print):
Data Types:
1. String: A sequence of characters enclosed within either single quotes (' ') or double quotes
(" "). In Python, strings are immutable, meaning they cannot be changed once created. They
are used to represent text data.
2. Integer: A whole number without any decimal points. Integers can be positive, negative, or
zero. They are used to represent numeric data.
Operators:
1.Input Operator: In Python, the input() function is used to take input from the user. It
prompts the user for input and returns a string containing the data entered by the user.
2. Print Operator: The print() function is used to display output to the user. It takes one or
more arguments and prints them as a single string.
CODE:
AIM: Conditional statements: Create a program that prompts the user for their age
and tells them if they can vote in the next election.
THEORY: Conditional statements are used to execute different blocks of code based on
whether a certain condition is true or false. In Python, the if, elif (short for "else if"), and else
keywords are used to create conditional statements.
In this program:
int(input("Enter your age: ")) prompts the user to enter their age, converts the input to an
integer, and stores it in the variable age.
if age >= 18: checks if the user's age is greater than or equal to 18. If it is, the program prints
"You are eligible to vote in the next election.".
If the condition age >= 18 is not true, the else block is executed, and the program prints "You
are not eligible to vote in the next election.".
CODE:
AIM: Loops: Create a program that calculates the factorial of a number entered by the
user using a loop.
THEORY: Loops are used to execute a block of code repeatedly as long as a certain
condition is true. In Python, two common types of loops are for loops and while loops.
for loops are used when you know the number of iterations in advance, such as iterating over
elements in a list or a range of numbers. While loops are used when you want to loop until a
specific condition is no longer true.
Factorial is a mathematical operation that multiplies a number by every integer smaller than
itself down to 1. It is denoted by the symbol '!', and it's used to find the product of all positive
integers up to a given positive integer.
CODE:
AIM: Lists and arrays: Create a program that prompts the user for a list of numbers
and then sorts them in ascending order.
THEORY:
Lists: Lists in Python are a collection of items that are ordered and mutable (modifiable).
Lists can contain elements of different data types, including numbers, strings, or even other
lists. Elements in a list are indexed, with the first element having an index of 0, the second
element having an index of 1, and so on.
Sorting:
Sorting is the process of arranging items in a specific order, such as ascending or descending
order. Python provides built-in functions like sorted() and methods like sort() to sort lists.
CODE:
def sort():
for i in range(0,len(arr)):
for j in range(i+1,len(arr)):
if(arr[i]>arr[j]):
temp=arr[i]
arr[i]=arr[j]
arr[j]=temp
sort()
for i in range(0,len(arr)):
print(arr[i],end=' ')
Experiment – 5
AIM: Strings and string manipulation: Create a program that prompts the user for a
string and then prints out the string reversed.
THEORY:
1. Strings in Python are sequences of characters, enclosed within either single quotes (' ') or
double quotes (" ").
2. Strings are immutable, meaning they cannot be changed after they are created. However,
you can create new strings based on existing strings.
3. Strings support various operations and methods for manipulation, such as concatenation,
slicing, and reversing.
CODE:
AIM: Functions: Create a program that defines a function to calculate the area of a
circle based on the radius entered by the user.
THEORY:
1. Functions in Python are reusable blocks of code that perform a specific task.
2. Functions can take input arguments (parameters), perform some computation, and
optionally return a result.
3. Defining a function involves using the def keyword followed by the function name, input
parameters (if any), and a block of code.
4. Functions can be called (invoked) multiple times from different parts of the program.
CODE:
AIM: Classes and objects: Create a program that defines a class to represent a car and
then creates an object of that class with specific attributes.
THEORY:
1. A class is a blueprint for creating objects. It defines the properties (attributes) and
behaviors (methods) that objects of the class will have.
2. An object is an instance of a class. It represents a specific instance of the class and has its
own unique set of attributes.
3. Attributes are variables that hold data associated with a class or an object.
Methods are functions defined within a class that perform operations on the class's data.
.
CODE:
def print_info(self):
print(f"This car is a {self.year} {self.make} {self.model}.")
AIM: File input/output: Create a program that reads data from a file and writes it to
another file in a different format.
THEORY:
1. File I/O operations in Python allow you to work with files on your computer's storage.
open() function is used to open a file.
2. It takes two arguments: the filename and the mode (e.g., 'r' for reading, 'w' for writing, 'a'
for appending).
3. read() and readlines() methods are used to read data from a file.
4. write() method is used to write data to a file.
5. close() method is used to close the file after performing file operations.
.
CODE:
# input.txt content
# This is line 1.
# This is line 2.
# This is line 3.
Experiment – 9
AIM: Regular expressions: Create a program that uses regular expressions to find all
instances of a specific pattern in a text file.
THEORY:
Regular Expressions: Regular expressions (regex) are sequences of characters that define a
search pattern. They are powerful tools for searching and manipulating strings. Python
provides the re module for working with regular expressions. Common regex operations
include searching for patterns, matching patterns, and replacing patterns in strings.
CODE:
def main():
file_path = 'sample_text.txt' # Update with your file path
pattern = r'\b\w+@\w+\.\w+\b' # Example pattern for finding email addresses
if __name__ == "__main__":
main()
AIM: Exception handling: Create a program that prompts the user for two numbers
and then divides them, handling any exceptions that may arise
THEORY:
1. Exception handling in Python allows you to gracefully handle errors and unexpected
situations that occur during program execution.
2. Python provides a try statement, which allows you to wrap code that might raise
exceptions.
3. The except clause is used to catch and handle specific exceptions that occur within the try
block.
4. You can also use the finally clause to execute cleanup code, regardless of whether an
exception occurred or not..
CODE:
AIM: GUI programming: Create a program that uses a graphical user interface (GUI)
to allow the user to perform simple calculations.
THEORY:
GUI programming stands for Graphical User Interface programming. It involves creating
applications that have graphical elements such as windows, buttons, menus, and other visual
components that users can interact with. GUI programming allows developers to build user-
friendly applications with intuitive interfaces, making it easier for users to interact with the
software.
Tkinter is a standard GUI (Graphical User Interface) library for Python. It is included with
most Python installations, so you don't need to install any additional packages to use it.
Tkinter provides a set of tools and widgets to create graphical user interfaces in Python
applications. Here's a brief overview of some key concepts related to Tkinter:
1. Widgets: Widgets are the building blocks of a Tkinter GUI. They are visual elements such
as buttons, labels, entry fields, checkboxes, radio buttons, etc. Tkinter provides a variety of
pre-built widgets that you can use to create your GUI.
2. Main Window: The main window is the primary window of a Tkinter application. It serves
as the container for all other widgets. You create the main window using the Tk() constructor
from the tkinter module.
3. Layout Management: Tkinter provides different layout managers to arrange widgets within
the main window. The most commonly used layout managers are pack(), grid(), and place().
pack() arranges widgets in a block or line, grid() arranges widgets in a table-like structure,
and place() allows you to specify the exact position of a widget.
CODE:
AIM: Web scraping: Create a program that uses a web scraping library to extract data
from a website and then stores it in a database.
THEORY: Web scraping is the process of extracting data from websites. It involves
retrieving web pages, parsing the HTML or XML content of those pages, and extracting the
desired information. Web scraping can be used to gather a wide range of data, including text,
images, links, and structured data like tables.
1. HTTP Requests: Web scraping begins with sending HTTP requests to a web server to
retrieve web pages. Python provides several libraries for making HTTP requests, such as
requests and urllib.
2. HTML Parsing: Once the web page is retrieved, its HTML content needs to be parsed to
extract the desired data. HTML parsing involves analyzing the structure of the HTML
document and identifying the elements containing the target data.
Python offers libraries like Beautiful Soup and lxml for parsing HTML and XML documents.
3. Data Extraction: After parsing the HTML content, you can use techniques like CSS
selectors or XPath expressions to locate specific elements in the HTML document and extract
data from them. Commonly extracted data include text, links, images, tables, and other
structured information.
4. Database Storage: Once the data is extracted, you may want to store it in a database for
further analysis or retrieval. Databases provide a structured and efficient way to organize and
manage large volumes of data. Python offers various database libraries such as sqlite3,
MySQLdb, psycopg2 (for PostgreSQL), and pymongo (for MongoDB) for interacting with
different types of databases.
CODE:
AIM: Data visualization: Create a program that reads data from a file and then creates
a visualization of that data using a data visualization library.
THEORY:
Data visualization is the graphical representation of data to provide insights and aid in
understanding patterns, trends, and relationships within the data. Python offers several
powerful libraries for data visualization, including Matplotlib, Seaborn, Plotly, and Bokeh.
These libraries allow you to create a wide range of visualizations, including line plots, scatter
plots, bar charts, histograms, and more.
1. Data Reading: Before you can visualize data, you need to read it from a file or another data
source. Python provides various tools and libraries for reading data from different file
formats, such as CSV, Excel, JSON, and databases.
2. Data Structures: Data is typically stored in data structures such as lists, arrays, pandas
DataFrames, or NumPy arrays. These data structures provide a convenient way to organize
and manipulate the data before visualization.
3. Data Visualization Libraries: Python offers several data visualization libraries, each with
its own strengths and capabilities. Some popular libraries include:
Matplotlib: A versatile plotting library that provides a MATLAB-like interface for creating
static, interactive, and animated visualizations.
Seaborn: Built on top of Matplotlib, Seaborn provides a high-level interface for creating
attractive statistical graphics.
CODE:
plt.show()
Experiment – 14
AIM: Machine learning: Create a program that uses a machine learning library to
classify images based on their content.
THEORY:
Machine Learning: Machine learning is a subfield of artificial intelligence (AI) that focuses
on developing algorithms and models that enable computers to learn from data and make
predictions or decisions without being explicitly programmed. Supervised learning is a
common approach in machine learning, where the model learns from labeled training data. In
image classification, each image in the training dataset is associated with a label or class.
Deep learning, a subset of machine learning, has revolutionized image classification with the
introduction of deep neural networks, particularly convolutional neural networks (CNNs),
which have shown remarkable performance in various computer vision tasks.
CODE:
THEORY:
Networking: Networking involves the exchange of data between multiple devices over a
network, such as the internet. Communication between a client (your program) and a server
typically occurs using a client-server architecture, where the client sends requests to the
server, and the server responds to those requests.
HTTP Requests: HTTP (Hypertext Transfer Protocol) is the protocol used for communication
between web clients (such as browsers or Python programs) and web servers.
HTTP requests are messages sent by a client to request resources or perform actions on a
server. Common types of HTTP requests include GET (retrieve data), POST (submit data),
PUT (update data), and DELETE (remove data).
Networking Libraries: Python provides several libraries for making HTTP requests and
interacting with web servers, including requests, urllib, and http.client. These libraries allow
you to send HTTP requests, handle responses, and perform various networking tasks such as
authentication, cookies, and sessions.
CODE:
AIM: Write a python script to print the current date in the following format “Sun May
2902:26:23 IST 2017”
THEORY:
datetime Module:
The datetime module in Python provides classes for working with dates, times, and their
combinations. The datetime class represents a point in time, and the datetime.now() method
returns the current date and time.
Formatting Dates:
Python provides the strftime() method (string format time) to format dates and times into
human-readable strings. The strftime() method takes a format string as an argument, which
contains format codes representing various components of the date and time, such as year,
month, day, hour, minute, second, etc.
CODE:
THEORY: Lists are one of the built-in data types in Python used to store collections of
items. They are ordered, mutable (modifiable), and can contain elements of different data
types. Lists are defined by enclosing comma-separated elements within square brackets [ ].
1. Creating Lists: You can create an empty list by simply using empty square brackets [].
To create a list with initial elements, enclose the elements within square brackets [ ] and
separate them by commas. Example: my_list = [1, 2, 3, 4, 5].
2. Appending Elements: The append() method is used to add elements to the end of a list.
Syntax: list.append(element) Example: my_list.append(6) adds the element 6 to the end of the
list my_list.
CODE:
THEORY:
Creation: Tuples are created by enclosing comma-separated elements within parentheses ().
Example: my_tuple = (1, 2, 3, 4, 5).
Accessing Elements: Elements of a tuple can be accessed using indexing and slicing, similar
to lists. Indexing starts from 0, and negative indexing starts from -1.
Example: first_element = my_tuple[0], last_element = my_tuple[-1].
CODE:
THEORY:
A dictionary in Python is a collection of key-value pairs. Each key is unique within the
dictionary, and it is used to access its corresponding value. Dictionaries are mutable, meaning
you can modify them after they've been created. They are unordered collections, meaning that
the order in which the key-value pairs are added to the dictionary may not be preserved.
Python dictionaries are very flexible and can store a wide variety of data types as values,
including integers, floats, strings, lists, tuples, other dictionaries, and more.
CODE:
THEORY:
Celsius (°C): Named after Swedish astronomer Anders Celsius, this scale sets the freezing
point of water at 0°C and the boiling point at 100°C under standard atmospheric pressure.
Fahrenheit (°F): Named after German physicist Daniel Gabriel Fahrenheit, this scale sets the
freezing point of water at 32°F and the boiling point at 212°F under standard atmospheric
pressure.
Conversion Formulas:
CODE:
AIM: Write a program that accepts the lengths of three sides of a triangle as inputs.
The program output should indicate whether or not the triangle is a right triangle
THEORY:
According to the Pythagorean theorem, in a right triangle, the square of the length of the
hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the lengths
of the other two sides.
CODE:
AIM: Write a python program to define a module and import a specific function in that
module to another program.
THEORY:
Defining a Module: To define a module in Python, you simply create a .py file and write
Python code inside it. The filename becomes the module name, and you can access its
contents using the import statement in other Python programs.
Importing Functions from a Module: When importing functions from a module, you can
either import the entire module or import specific functions from the module.
Importing specific functions can make your code more readable and reduce namespace
clutter.
CODE:
THEORY: Roman Numerals: Roman numerals are a numeral system originating from
ancient Rome. They are represented by combinations of letters from the Latin alphabet.
The basic Roman numerals and their corresponding decimal values are:
I: 1
V: 5
X: 10
L: 50
C: 100
D: 500
Roman numerals follow specific rules for representation, including additive and subtractive
notations.
CODE:
# Example usage:
converter = IntegerToRoman()
print(converter.int_to_roman(354)) # Output: CCCLIV
Experiment – 24
THEORY:
Reversing a String Word by Word: To reverse a string word by word means to reverse the
order of words while keeping each word unchanged.
For example, if we have the string "Hello World", the reversed string would be "World
Hello".
Approach:
One approach to reverse a string word by word is to split the string into words, reverse the
order of the words, and then join them back together into a single string.
We can achieve this using Python's string manipulation methods such as split() and join().
Another approach is to iterate through the string character by character, building each word,
and then reversing the order of the words.
CODE:
# Example usage
reverser = ReverseWords()
reversed_string = reverser.reverse_words("Hello world, how are you?")
print(reversed_string)
Experiment – 25
THEORY: Linear search, also known as sequential search, is a simple searching algorithm
that searches for a target value in a list or array by sequentially checking each element from
the beginning until the target is found or the end of the list is reached.
Linear search works well for small-sized lists or unsorted arrays where the elements are not
arranged in any particular order.
Algorithm:
1. The linear search algorithm traverses the list or array linearly, comparing each element
with the target value until a match is found or the end of the list is reached.
2. If the target value is found, the algorithm returns the index of the element where the match
occurred.
3. If the target value is not found, the algorithm returns a special value (e.g., -1) to indicate
that the target is not present in the list.
Time Complexity:
In the worst-case scenario, linear search has a time complexity of O(n), where n is the
number of elements in the list or array.
This means that the time taken to search for a target value increases linearly with the size of
the list.
CODE:
# Example usage
data = [10, 20, 30, 40, 50]
target = 30
index = linear_search(data, target)
if index != -1:
print(f"Target {target} found at index {index}")
else:
print(f"Target {target} not found in the list")
Experiment – 26
THEORY: Binary search is an efficient searching algorithm that works on sorted arrays. It
repeatedly divides the search interval in half until the target element is found or the interval is
empty.
Algorithm:
1. Compare the target value with the middle element of the array.
2. If the target value matches the middle element, return its index.
3. If the target value is greater than the middle element, then the target must be in the right
half of the array; repeat the search in the right half.
4. If the target value is smaller than the middle element, then the target must be in the left half
of the array; repeat the search in the left half.
5. Continue this process until the target value is found or the search interval is empty.
Time Complexity:
Binary search has a time complexity of O(log n) in the worst-case scenario, where n is the
number of elements in the array.
This efficiency makes binary search particularly suitable for large datasets
CODE:
THEORY:
Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a
time. It works by iterating through the array, removing one element at a time and inserting it
into its correct position in the sorted part of the array. The key idea is to maintain a sorted
sublist in the lower positions of the array, shifting larger elements up as necessary to make
room for the inserted element.
Algorithm:
1. Start with the second element of the array and assume it is the first element of the sorted
sublist.
2. Compare this element with the elements in the sorted sublist, moving from right to left.
3. Insert the element into its correct position in the sorted sublist by shifting larger elements
to the right.
4. Repeat this process for each element in the array until the entire array is sorted.
Time Complexity:
In the worst-case scenario, insertion sort has a time complexity of O(n^2), where n is the
number of elements in the array.
It performs well for small datasets or nearly sorted arrays but becomes inefficient for large
datasets compared to more advanced sorting algorithms like merge sort or quicksort.
CODE:
# Example usage:
arr = [12, 11, 13, 5, 6]
print("Original array:", arr)
sorted_arr = insertion_sort(arr)
print("Sorted array:", sorted_arr)
Experiment – 28
THEORY:
Selection sort is a simple sorting algorithm that divides the input list into two parts: the sorted
sublist and the unsorted sublist. It repeatedly finds the minimum element from the unsorted
sublist and swaps it with the first unsorted element. After each iteration, the sorted sublist
grows, and the unsorted sublist shrinks until the entire list is sorted.
Algorithm:
1. Start with the entire list considered as the unsorted sublist.
2. Find the minimum element in the unsorted sublist.
3. Swap the minimum element with the first element of the unsorted sublist.
4. Repeat this process for the remaining unsorted sublist until the entire list is sorted.
Time Complexity:
Selection sort has a time complexity of O(n^2) in all cases, where n is the number of
elements in the list.
It performs the same number of comparisons and swaps regardless of the initial order of the
elements.
CODE:
# Example usage:
arr = [64, 25, 12, 22, 11]
print("Original array:", arr)
sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_arr)
Experiment – 29
THEORY:
The Tower of Hanoi is a classic problem in computer science and mathematics. It consists of
three rods and a number of disks of different sizes that can slide onto any rod. The objective
is to move the entire stack of disks from one rod to another, obeying the following rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the top disk from one stack and placing it on top of another
stack.
3. No disk may be placed on top of a smaller disk.
Recursive Approach: The Tower of Hanoi problem can be solved using a recursive approach.
To solve the problem for n disks, we can follow these steps:
1. Move the top n - 1 disks from the source rod to an auxiliary rod, using the destination rod
as a helper.
2. Move the nth disk from the source rod to the destination rod.
3. Move the n - 1 disks from the auxiliary rod to the destination rod, using the source rod as a
helper.
4. This process is repeated recursively until all disks are moved to the destination rod.
Time Complexity:
The time complexity of the Tower of Hanoi problem is O(2^n), where n is the number of
disks. This exponential time complexity arises from the recursive nature of the problem.
CODE:
# Example usage:
n=3
tower_of_hanoi(n, 'A', 'C', 'B')
Experiment – 30
THEORY:
Time Complexity:
The time complexity of matrix multiplication is O(n^3), where n is the size of the matrices.
This arises from the three nested loops used to iterate over the rows and columns of the
matrices.
CODE: