0% found this document useful (0 votes)
7 views34 pages

Final File Python

The document outlines various Python programming tasks and concepts, including salary calculations, data types, control structures, file handling, object-oriented programming, and exception handling. Each section includes practical examples and programs to illustrate the concepts, emphasizing Python's simplicity and efficiency compared to other languages like C. The document serves as a comprehensive guide for beginners to understand and implement Python programming effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views34 pages

Final File Python

The document outlines various Python programming tasks and concepts, including salary calculations, data types, control structures, file handling, object-oriented programming, and exception handling. Each section includes practical examples and programs to illustrate the concepts, emphasizing Python's simplicity and efficiency compared to other languages like C. The document serves as a comprehensive guide for beginners to understand and implement Python programming effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basics of Python(LO1)

14/01/2026

Aim
Write a Python program to calculate the gross salary of an employee. The program should
prompt the user for the basic salary (BS) and then compute the dearness allowance (DA) as
70% of BS, the travel allowance (TA) as 30% of BS, and the house rent allowance (HRA) as
10% of BS. Finally, it should calculate the gross salary as the sum of BS, DA, TA, and HRA
and display the result.

2 Write a Python program to calculate the simple interest based on user input. The program
should prompt the user to enter the principal amount, the rate of interest, and the time period
in years. It should then compute the simple interest using the formula Simple Interest
(Principal Rate Time) /100 and display the result.

Theory

Basics of Python
1. Introduction to Python
Python is a high-level, interpreted, general-purpose programming language known for its
simple syntax and readability. It supports procedural, object-oriented, and functional
programming styles, making it suitable for both beginners and advanced users.

Key Points:

● High-level and interpreted


● Easy to read and write
● Multi-paradigm language

2. Importance of Python
Python is important because it reduces development time and coding complexity. Its large
ecosystem of libraries allows programmers to build applications quickly in areas such as data
science, artificial intelligence, automation, and web development. Python programs are also
platform-independent.

Key Points:

● Faster development
● Large library support
● Cross-platform compatibility
3. Uses of Python
Python is widely used for automation, web development, data analysis, machine learning, and
scientific computing. Due to its simplicity, it is also commonly used in education as a first
programming language.

Key Points:

● Automation and scripting


● Web and backend development
● Data science and AI
● Educational purposes

4. Difference Between C and Python


C is a low-level, compiled language focused on performance and hardware control, while
Python is a high-level, interpreted language focused on ease of use. Memory management in
C is manual, whereas Python uses automatic garbage collection. C is faster, but Python is
easier to learn and use.

Key Points:

● C is faster; Python is simpler


● C uses manual memory management
● Python uses automatic memory management

5. Libraries in Python
Libraries in Python are collections of pre-written code that help perform common tasks
efficiently. They allow programmers to reuse code and implement complex functionalities
without writing everything from scratch.

Key Points:

● Save time and effort


● Provide reusable functions and modules
● Improve efficiency

Program: Gross Salary Calculator


# Gross Salary Calculator
bs = float(input("Enter Basic Salary (BS): "))
da = 0.70 * bs
ta = 0.30 * bs
hra = 0.10 * bs
gross_salary = bs + da + hra + ta
print("\n----- Salary Breakdown ")
print("Basic Salary :", bs)
print("Dearness Allowance (DA):", da)
print("Travel Allowance (TA):", ta)
print("House Rent Allowance (HRA):", hra)
print("Gross Salary :", gross_salary)
Output

Program 2

p = float(input("Principal: "))
r = float(input("Rate: "))
t = float(input("Time: "))
si = (p*r*t)/100
print("Simple Interest =", si)

Conclusion;
The program for calculating allowance such as travelling and dearness’ and calculation of
simple interest was successfully implemented using Python. Through this experiment, the
basic syntax, variables, data types, operators, and input/output functions were clearly
understood. Python proved to be simple, readable, and efficient compared to traditional
languages like C, making it suitable for beginners and rapid application development.
Basics of Python – Task List Management (LO1) (14/01/2026)

Aim
1. Develop a Python program to manage a task list using lists and tuples, including adding, removing,
updating, and sorting tasks.

2. Create a Python code to demonstrate the use of sets and perform set operations (union,
intersection, difference) to manage student enrolments in multiple courses / appearing for multiple
entrance exams like CET JEE NEET etc.

3. Write a Python program to create, update, and manipulate a dictionary of student records, including
their grades and attendance.

Theory
Built-in Data Types in Python

1. Introduction to Built-in Data Types

Built-in data types in Python are predefined data structures that allow storage and manipulation of different kinds of
data. Python automatically assigns a data type to a variable based on the value stored in it. These data types help in
organizing data efficiently and performing appropriate operations on them.

Key Points:

● Predefined in Python
● No need for explicit declaration
● Type is assigned automatically

2. Numeric Data Types

Numeric data types are used to store numerical values. Python supports integers for whole numbers, floating-
point numbers for decimal values, and complex numbers for mathematical and scientific calculations.

Key Points:

● int → whole numbers


● float → decimal numbers
● complex → numbers with real and imaginary parts

3. Boolean Data Type


The Boolean data type represents logical values. It is mainly used in decision-making and conditional
statements. Boolean values in Python are written as True and False.

Key Points:

● Only two values: True and False


● Used in conditions and loops
● Result of comparison operations

4. String Data Type

A string is a sequence of characters enclosed within single quotes, double quotes, or triple quotes.
Strings are used to store textual data such as names, messages, and sentences. Strings in Python are
immutable, meaning their values cannot be changed once created.

Key Points:

● Stores text data


● Written using quotes
● Immutable in nature

5. List Data Type

A list is an ordered and mutable collection of elements. It can store multiple values of different data
types in a single variable. Lists are widely used because their elements can be modified after creation.

Key Points:

● Ordered collection
● Mutable (changeable)
● Allows duplicate elements

6. Tuple Data Type

A tuple is similar to a list but is immutable. Once a tuple is created, its elements cannot be
changed. Tuples are used when data needs to be protected from modification.

Key Points:

● Ordered collection
● Immutable
● Faster than lists

7. Set Data Type

A set is an unordered collection of unique elements. Sets are mainly used to eliminate duplicate
values and perform mathematical set operations such as union and intersection.

Key Points:
● Unordered collection
● No duplicate elements
● Mutable but elements must be immutable

8. Dictionary Data Type

A dictionary stores data in key-value pairs. Each key must be unique and is used to access its
corresponding value. Dictionaries are commonly used to represent structured data such as records.

Key Points:

● Stores data as key-value pairs


● Keys are unique
● Mutable and unordered

Program

tasks = []

[Link](("Task 1",

4))

[Link](("Task 2", 2))

[Link](("Task 3", 1))

[Link](("Task 4", 3))

# Sort by priority number

(ascending)

[Link](key=lambda task:

task[1])

for task, priority in tasks:

print(f"{task} has priority {priority}")

―――――――――――――――――――――――――――――――――――――――――

Program 2cet = {"A", "B", "C"}

jee = {"B", "C", "D"}

print("Union:", cet | jee)

print("Intersection:",

cet&jee)

print("Difference:", cet -

jee)
Program 3

students = {"101": {"Name": "Amit", "Marks": 90}}

# 1. Adding a new student

students["102"] = {"Name": "Neha", "Marks":

95} # 3. keys()

print("Student IDs:",

[Link]()) # 4. values()

print("Student Details:",

[Link]()) # 5. items()

print("All Students:")

for roll, details in [Link]():

print(f"Roll No: {roll}, Name: {details['Name']}, Marks:

{details['Marks']}") # 6. update()

[Link]({"103": {"Name": "Rahul", "Marks":

88}}) # 7. pop() – remove a student

[Link]("10

1") # 8. len()

print("Total Students:",

len(students)) # 9. copy()

students_copy = [Link]()

print("Final Dictionary:",

students_copy)

―――――――――――――――――――――――――――――――――――――――――

――――――――――—
Output

―――――――――――――――――――――――――――――――――――――――――

―――――――――――—

Conclusion
The program was successfully implemented using Python. The concepts of syntax, variables,
data types, operators, and input/output were clearly understood through practical execution.

Python provides several built-in data types to store and manage different kinds of data
efficiently. Choosing the appropriate data type improves program clarity, performance, and
reliability.
Control Structures (LO2) (23/01/2026)

Aim
1. Write a Python program to print a triangle pattern, emphasizing the transition from C to
Python syntax.
2. Design a Python program to compute the factorial of a given integer N.

Theory
Control structures are fundamental components of programming languages that control the
flow of execution of a program. They determine how statements are executed sequentially,
conditionally, or repeatedly. In Python, control structures play a crucial role in
decision-making, looping, and logical branching. There are three main types of control
structures: sequential, selection, and iteration. Sequential control structures execute
statements line by line in the order in which they are written. Selection control structures
allow a program to choose between different paths based on conditions. In Python, this is
implemented using if, if-else, and elif statements. Iteration control structures enable
repeated execution of a block of code until a condition is satisfied, using for and while
loops. Control structures are used whenever a program needs to make decisions, perform
repetitive tasks, or manage multiple execution paths. Examples include pattern printing,
factorial calculation, data validation, and searching algorithms. Python simplifies the use of
control structures by eliminating semicolons and curly braces, relying instead on
indentation to define code blocks. Program 1: Triangle Pattern
n=5
for i in range(1, n + 1):
print("*" * i)

Program 2: Factorial of a Number


n = int(input("Enter a number: "))
fact = 1
for i in range(1, n + 1):
fact = fact * i
print("Factorial:", fact)

Output

CONCLUSION
The Python programs were successfully executed using appropriate control structures.
Loops were effectively used for pattern generation and factorial computation. The
transition from C to Python syntax highlights Python’s simplicity, readability, and use of
indentation instead of braces. Control structures form the backbone of logical program
design and are essential for developing efficient and structured Python programs.
File Handling (LO3) (06/02/2026)
Aim
1. Develop a Python program that reads a text file and prints words of specified lengths
(e.g., three, four, five, etc.) found within the file.
2. Write a Python program to take a file which contains city names on each line,
alphabetically sort the city names, and write them into another file.

Theory
File handling in Python allows reading and writing data from files stored on disk. Using
open() function, files can be opened in different modes such as read (r), write (w), and
append (a). In the first program, the file is read and each word is extracted and checked for
its length. Conditional statements are used to print words matching the specified length. In
the second program, a file containing city names is read line by line. The list of city names
is sorted alphabetically using the sort() method, and the sorted data is written into another
file. File handling operations ensure proper data storage and retrieval.

Program 1: Print Words of Specified Length


# Program to print words of specified length
length = 4

file = open("[Link]", "r")


data = [Link]()
[Link]()

words = [Link]()
print("Words with length", length, ":")
for word in words:
if len(word) == length:
print(word)

Program 2: Sort City Names Alphabetically


# Program to sort city names
file = open("[Link]", "r")
cities = [Link]()
[Link]()
cities = [[Link]() for city in cities]
[Link]()
file = open("sorted_cities.txt", "w")
for city in cities:
[Link](city + "\n")
[Link]()

print("Cities sorted successfully.")

Output
Conclusion
The programs successfully demonstrated file reading and writing operations in Python. The
first program filtered words based on specified length, while the second program sorted
city names alphabetically and stored them in another file. File handling plays a crucial role
in data processing applications.

Object Oriented Programming(LO4)


13/02/2026

Aim
Design a system using classes for vehicle rental agencies and rental transactions using
Python.

Theory
Object Oriented Programming (OOP) is a programming paradigm that focuses on using
objects and classes to design and organize software programs. Instead of writing programs
as a sequence of instructions, OOP models programs around real-world entities. Each
entity is represented as an object that contains both data and functions that operate on that
data. A class acts as a blueprint for creating objects. It defines the attributes and methods
that the objects created from it will have. An object is an instance of a class. For example,
in a vehicle rental system, a class named Vehicle can represent different vehicles such as
cars and bikes, while another class can represent rental transactions.
olymorphism allows methods to perform different tasks depending on the object that calls
them. OOP is widely used in modern programming because it improves code organization,
reusability, and maintainability. By using classes and objects, developers can build
scalable and efficient software applications.

Program
class Vehicle:
def init (self, name, price_per_day): [Link]
= name
self.price_per_day = price_per_day
class RentalAgency:
def init (self):
[Link] = []

def add_vehicle(self, vehicle):


[Link](vehicle)

def show_vehicles(self):
print("Available Vehicles:")
for v in [Link]:
print([Link], "-", v.price_per_day, "per day")

class RentalTransaction:
def init (self, customer, vehicle, days):
[Link] = customer
[Link] = vehicle
[Link] = days

def calculate_cost(self):
return [Link].price_per_day * [Link]
# Create vehicles
car = Vehicle("Car", 1000)

bike = Vehicle("Bike", 500)


# Create rental agency
agency = RentalAgency()
agency.add_vehicle(car)
agency.add_vehicle(bike)
agency.show_vehicles()

# Rental transaction
transaction = RentalTransaction("Rahul", car, 3)

print("\nCustomer:", [Link])
print("Vehicle Rented:", [Link])
print("Days:", [Link])
print("Total Cost:", transaction.calculate_cost())

output

Conclusion;

This program demonstrates a simple vehicle rental system using object-oriented programming
in Python. It defines separate classes for vehicles, the rental agency, and rental transactions,
ensuring a clear separation of responsibilities. The system allows adding and displaying
available vehicles and calculates the rental cost based on the number of days. Overall, it
effectively illustrates core OOP concepts such as encapsulation, modularity, and abstraction,
while serving as a basic foundation for building more advanced rental management systems.
Exception Handling (LO3)
(22/02/2026)
Aim
Demonstrate the use of Python exception handling using a sample program with an
intentional error.

Theory
Exception handling in Python is a mechanism that allows programmers to handle runtime
errors in a controlled way. During the execution of a program, unexpected situations such
as invalid input, division by zero, or missing files may occur. These situations are called
exceptions. If exceptions are not handled properly, the program may terminate abruptly and
produce an error message. Python provides special keywords such as try, except, finally,
and raise to handle exceptions. The try block contains the code that might produce an error.
If an error occurs, control is transferred to the except block, where the error can be handled
gracefully. The raise keyword is used to manually trigger an exception when a specific
condition occurs in the program. Exception handling is useful when programs interact with
user input or external data sources. For example, a program may need to validate whether a
user has entered a correct value. If the value does not satisfy certain conditions, an
exception can be raised and handled appropriately. Using exception handling improves
program reliability and prevents the program from crashing. In practical applications,
exception handling is widely used in systems such as banking applications, login systems,
and data validation programs.

Program
# Demonstration of Built-in Exceptions and Exception Handling

print("TypeError : Raised when an operation is applied to an object of incorrect type.")


print("ValueError : Raised when a function gets an argument of correct type but improper
value.")
print("ImportError : Raised when the imported module is not found.")
print("IndexError : Raised when the index of a sequence is out of range.")
print("KeyError : Raised when a key is not found in a dictionary.")

print("-------------------------------------------------------------")
# TypeError Example
try:
result = "Hello" + 5 # Attempting to add string and integer
print(result)
except TypeError as te:
print("TypeError caught:", te)
print("-------------------------------------------------------------")

# ValueError Example
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError as ve:
print("ValueError caught:", ve)

print("-------------------------------------------------------------")
# ImportError Example
try:
import non_existing_module
except ImportError as ie:
print("ImportError caught:", ie)

print("-------------------------------------------------------------")

# IndexError Example
numbers = [1, 2, 3]
try:
print(numbers[5]) # Index out of range
except IndexError as ie:
print("IndexError caught:", ie)
print("-------------------------------------------------------------")

# KeyError Example
student = {"name": "Alice", "age": 20}

try:
print(student["grade"]) # Key doesn't exist
except KeyError as ke:
print("KeyError caught:", ke)

CONCLUSION:-

This program demonstrates the handling of common runtime exceptions in Python using try-
except blocks. It covers five key error types: TypeError, ValueError, ImportError, IndexError,
and KeyError, each triggered through a specific faulty operation.
By catching these exceptions, the program prevents abrupt termination and ensures graceful
error handling with meaningful messages. This highlights the importance of exception
handling in writing robust and reliable programs, allowing developers to manage unexpected
situations effectively and maintain program flow
Arrays (LO6)
22/02/2026

Aim
1. Write a Python program to create 1D, 2D and 3D arrays and perform basic operations
like slicing, indexing, dot product and cross product.
2. Develop a Python script to create two arrays of the same shape and perform
element-wise subtraction, addition, multiplication and division.

Theory
Arrays are an important data structure used to store multiple values in a single variable. In
Python, arrays are commonly implemented using the NumPy library, which provides
powerful tools for numerical computations and data manipulation. NumPy arrays allow
efficient storage and processing of large datasets compared to normal Python lists. Arrays
can exist in multiple dimensions. A one-dimensional array contains elements arranged in a
single row, similar to a list. A two-dimensional array represents data in rows and columns
and is commonly used to represent matrices or tables. A three-dimensional array extends
this concept by adding another level of depth, which is useful for representing complex
data structures such as image data or scientific datasets. NumPy provides several built-in
functions that allow mathematical operations on arrays. Operations such as indexing and
slicing allow programmers to access specific elements or sections of an array.
Mathematical operations such as dot product and cross product are useful in vector
calculations, physics simulations, and machine learning algorithms. Another powerful
feature of NumPy is element-wise operations. This makes numerical computation efficient
and concise. Arrays are widely used in fields such as data science, machine learning,
engineering simulations, image processing, and scientific computing. Because of their
efficiency and flexibility, arrays form the foundation of many modern data processing and
analytical applications.

Program 1
import numpy as np
# create 3D array
array3 = [Link]([
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
])

print("3D Array:")
print(array3)
print(" ")
# reshaping 1D array into 2x2
array1 = [Link]([1,2,3,4])
reshaped = [Link](2, 2)

print("Reshaped Array (2x2):")


print(reshaped)

print(" ")
# Dot and Cross Product
v1 = [Link]([1, 2, 3])
v2 = [Link]([4, 5, 6])
print("Dot Product:", [Link](v1, v2))
print("Cross Product:", [Link](v1, v2))

Output

Program 2
import numpy as np

array1 = [Link]([[1, 3, 5],


[7, 9, 11]])

array2 = [Link]([[2, 4, 6],


[8, 10, 12]])

print("Array 1:")
print(array1)

print("Array 2:")
print(array2)

print(" ")
print("Addition:")
print(array1 + array2)

print(" ")

print("Subtraction:")
print(array1 - array2)

print(" ")
print("Multiplication:")
print(array1 * array2)

print(" ")

print("Division:")
print(array1 / array2)
Output

Conclusion
The experiment successfully demonstrated the use of arrays in Python using the NumPy
library. Different types of arrays such as 1D, 2D, and 3D arrays were created and
operations such as reshaping, dot product, and cross product were performed. Element-
wise arithmetic operations between two arrays were also implemented, showing the
efficiency and usefulness of NumPy arrays in numerical computation.
[Link] 27/2/26
AIM:-1. Write a program to implement the filing of student form.

2. Develop a Python GUl application that performs various unit conversions such as currency
(Rupees to Dollars), temperature (Celsius to Fahrenheit), and length (Inches to Feet). The
application should include input fields for the values, dropdown menus or buttons to select the
type of conversion, and labels to display the results.

THEORY:-

1. GUI applications in Python follow an event-driven programming model, where the program
waits for user actions such as clicking a button, entering text, or selecting an option.

2. Events trigger specific functions that handle the user’s action, for example processing data
when a “Submit” button is clicked.

3. Widgets are the main components of a GUI, including elements like buttons, labels, text
fields, checkboxes, and menus.

4. Libraries such as Tkinter and PyQt provide tools to create GUI applications, allowing
developers to design user-friendly programs like calculators, login forms, and small desktop
applications.

1. Write a program to implement the filing of student form.

INPUT:-

import tkinter as tk

from tkinter import

ttk

def submit_form():

name =
name_entry.get() age

= age_entry.get()

gender =

gender_var.get()

subjects = []

if math_var.get():
[Link]("Math

s") if Science_var.get():

[Link]("Scienc

e") if History_var.get():

[Link]("History")

grade = grade_combobox.get()

[Link]([Link], f"Name: {name}\n")

[Link]([Link], f"Age: {age}\n")

[Link]([Link], f"Gender: {gender}\n")


[Link]([Link], f"Subjects: {', '.join(subjects)}\n")

[Link]([Link], f"Grade: {grade}\n")

[Link]([Link], "-" * 30 + "\n")

root = [Link]()

[Link]("Student

Form")

[Link]("400x5

00")

[Link](root, text="Name:").place(x=20,
y=20) name_entry = [Link](root,

width=30) name_entry.place(x=120, y=20)

[Link](root, text="Age:").place(x=20, y=60)

age_entry = [Link](root, width=30)

age_entry.place(x=120, y=60)
[Link](root, text="Gender:").place(x=20, y=100)

gender_var = [Link](value="None")

[Link](root, text="Male", variable=gender_var, value="Male").place(x=120, y=100)

[Link](root, text="Female", variable=gender_var, value="Female").place(x=200,

y=100)

[Link](root, text="Subjects:").place(x=20, y=140)

math_var = [Link]()

Science_var = [Link]()

History_var = [Link]()

[Link](root, text="Maths", variable=math_var).place(x=120, y=140)


[Link](root, text="Science", variable=Science_var).place(x=120, y=170)

[Link](root, text="History", variable=History_var).place(x=120, y=200)

[Link](root, text="Grade").place(x=20, y=240)

grade_combobox = [Link](root, values=["A", "B", "C", "D", "E"], state="readonly")

grade_combobox.place(x=120, y=240)

submit_button = [Link](root, text="Submit", command=submit_form)

submit_button.place(x=150, y=280)

textbox = [Link](root, width=40, height=10)

[Link](x=20, y=320)

[Link]()

OUTPUT:-
2. Develop a Python GUl application that performs various unit conversions such
as currency (Rupees to Dollars), temperature (Celsius to Fahrenheit), and length
(Inches to
Feet). The application should include input fields for the values, dropdown menus or
buttons to select the type of conversion, and labels to display the results.
INPUT:-

from tkinter import

* root = Tk()
[Link]("Unit Converter")

[Link]("350x250")
conversion = StringVar()

[Link]("Rupees to

Dollars")
def convert():

value = float(entry_value.get())

if [Link]() == "Rupees to

Dollars": result = value / 83 # approx

rate

result_label.config(text="Result: " + str(round(result,2)) + " Dollars")

elif [Link]() == "Celsius to Fahrenheit":

result = (value * 9/5) + 32

result_label.config(text="Result: " + str(round(result,2)) + " °F")

elif [Link]() == "Inches to

Feet": result = value / 12

result_label.config(text="Result: " + str(round(result,2)) + "

Feet") Label(root, text="Unit Converter",

font=("Arial",16)).pack(pady=10) Label(root, text="Enter

Value").pack()
entry_value =

Entry(root)

entry_value.pack()

Label(root, text="Select
Conversion").pack(pady=5) OptionMenu(root,

conversion,

"Rupees to Dollars",

"Celsius to Fahrenheit",

"Inches to Feet").pack()

Button(root, text="Convert", command=convert).pack(pady=10)

result_label = Label(root, text="Result: ")

result_label.pack()

[Link]()
OUTPUT:-

CONCLUSION:-

GUI (Graphical User Interface) in Python allows users to interact with programs using visual
elements such as windows, buttons, menus, icons, and text boxes instead of typing
[Link] makes software easier and more interactive, as users can perform tasks by
clicking buttons, selecting options, or entering data in input fields.

Python provides several libraries for GUI development, including Tkinter, PyQt, Kivy, and
wxPython. These libraries offer ready-made components called widgets like buttons, labels,
and text [Link] programs are event-driven and use layout managers, where the program
responds to user actions (events) and arranges widgets properly inside the main window to
create a neat and user-friendly interface.
[Link] AND MATPLOTLIB(LO6)
20/03/2026
AIM:-Using the Iris Data ([Link] perform the
following tasks

Read the first 8 rows of the dataset,Display the column names of the Iris dataset,Fill any
missing data with the mean value of the respective column,Remove rows that contain any
missing values,Calculate and display the mean, minimum, and maximum values of the Sepal
length column.

Using the Cars Data (hutips//[Link]/datasets/nameecrafatima/toyotacsv),perform


the following tasks

[Link] a scatter plot between the Age and Price of the cars to illustrate how the price decreases
as the age of the car increases,Generate a histogram to show the frequency distribution of
kilometres driven by the cars,Produce a bar plot to display the distribution of cars by fuel
type,Create a pie chart to represent the percentage distribution of cars based on fuel types,Draw
a box plot to visualize the distribution of car prices across different fuel types.

THEORY:-

Data analysis in Python involves a systematic process of collecting, cleaning, transforming,


and visualizing data to extract meaningful insights. This is primarily achieved using libraries
such as Pandas for data manipulation, NumPy for numerical computations, and Matplotlib
or Seaborn for data visualization. The first step in analysis is loading the dataset, typically
using functions like read_csv(), followed by examining its structure through methods such
as .head() and
.columns to understand the features present.. Once the dataset is cleaned, descriptive statistical
measures such as mean, minimum, and maximum are computed to summarize the data and
understand its distribution.

In addition to preprocessing, data visualization plays a vital role in interpreting patterns and
relationships within the dataset. Graphical techniques such as scatter plots help identify
correlations between variables, histograms illustrate frequency distributions, bar plots represent
categorical data comparisons, pie charts show proportional distributions, and box plots provide
insights into data spread, central tendency, and outliers. These visualization methods enable
better understanding of trends, such as the relationship between car age and price or the
distribution of fuel types. Overall, the combination of data cleaning, statistical analysis, and
visualization forms the foundation of exploratory data analysis (EDA), which is essential for
making informed decisions and building reliable data-driven models.
INPUT:-

import pandas as

pd # Load

dataset

df = pd.read_csv('[Link]') # ensure correct file

name print("First 8 rows:\n", [Link](8))

print("\nColumn Names:\n", [Link])

# iii. Fill missing values with mean (only numeric columns)

df_filled = [Link]()

df_filled.fillna(df_filled.mean(numeric_only=True),

inplace=True)

# iv. Remove rows with missing

values df_dropped = [Link]()

# v. Mean, Min, Max of Sepal Length

# Column name may be 'SepalLengthCm' in Kaggle

column_name = 'SepalLengthCm' if 'SepalLengthCm' in [Link] else 'sepal_length'

print("\nSepal Length Statistics:")

print("Mean:",

df[column_name].mean())

print("Min:",

df[column_name].min())

print("Max:", df[column_name].max())
OUTPUT:-

INPUT:-

import pandas as pd

import [Link] as plt

# Load dataset

df = pd.read_csv('[Link]', na_values=['??'])

# Preview columns (debug

step) print("Columns:",

[Link])

# Fix column naming dynamically


age_col = 'Age_08_04' if 'Age_08_04' in [Link] else 'Age'

# --- Task i: Scatter Plot (Age vs Price) ---

[Link](figsize=(8,6))

[Link](df[age_col], df['Price'],

alpha=0.5) [Link]('Age of Car

(months)') [Link]('Price')

[Link]('Price vs Age of Cars')


[Link](True)

[Link]()

# --- Task ii: Histogram of KM

---[Link](figsize=(8,6))
[Link](df['KM'].dropna(), bins=15, edgecolor='black')

[Link]('Kilometers Driven')

[Link]('Frequency')

[Link]('Distribution of Kilometers Driven')

[Link](axis='y', linestyle='--')

[Link]()

# --- Task iii: Bar Plot of Fuel Type ---

fuel_counts =
df['FuelType'].value_counts()

[Link](figsize=(8,6))
fuel_counts.plot(kind='bar')

[Link]('Fuel Type')

[Link]('Number of Cars')
[Link]('Distribution of Cars by Fuel Type')

[Link](rotation=0)

[Link]()

# --- Task iv: Pie Chart ---

[Link](figsize=(8,8))

fuel_counts.plot(kind='pie',

autopct='%1.1f%%') [Link]('Fuel Type

Distribution')

[Link]('')

[Link]()

# --- Task v: Box Plot ---

[Link](figsize=(8,6))

[Link](column='Price',

by='FuelType') [Link]('Price Distribution

by Fuel Type') [Link]('')

[Link]('Price')

[Link]()

OUTPUT:-
CONCLUSION:-

Data analysis in Python involves a systematic process of collecting, cleaning, transforming,


and visualizing data to extract meaningful insights. This is primarily achieved using libraries
such as Pandas for data manipulation, NumPy for numerical computations, and Matplotlib
or Seaborn for data visualization. The first step in analysis is loading the dataset, typically
using functions like read_csv(), followed by examining its structure through methods such
as .head() and
.columns to understand the features present. Handling missing data is a crucial preprocessing
step, which can be done either by replacing missing values with statistical measures like the
mean or by removing incomplete records to maintain data quality. Once the dataset is cleaned,
descriptive statistical measures such as mean, minimum, and maximum are computed to
summarize the data and understand its distribution.
[Link] MATCH(LO5) (23/03/2026)
AIM:-Write a Python script that prompts the user to create a password. Use regular expressions
to validate the password based on these criteria. At least & characters long, Contains at least
one uppercase letter, one lowercase letter one digit, and one special character.

THEORY:-

Regular Expressions (Regex)

Regular expressions (Regex) are formal pattern specifications used to identify, validate, and
manipulate strings based on defined rules. They are extensively used in areas such as:

● Input validation (e.g., passwords, emails, phone numbers)


● Data extraction from large text corpora
● Search-and-replace operations
● Lexical analysis in

compilers A regex pattern is

composed of:

● Literals → exact characters (abc, 123)


● Metacharacters → special symbols with meaning (. ^ $ * + ? { } [ ] \ | ( ))
● Character classes → sets of characters ([a-z], [A-Z], [0-9])
● Quantifiers → define repetition (*, +, {n}, {n,m})
● Assertions → conditions without consuming characters (e.g., lookaheads)

1. Write a program to implement the filing of student form.

INPUT:-
import re

import tkinter as tk

from tkinter import messagebox

username_pattern = r"^[A-Za-z][A-Za-z0-9_]{2,14}$"

password_pattern = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%!^&*]).{8,20}$"

def validate():
username = entry_username.get()

password = entry_password.get()

if not [Link](username_pattern, username):

[Link]("Invalid Username", "Invalid Username")

return

if not [Link](password_pattern, password):

[Link]("Invalid Password", "Invalid Password")

return

[Link]("Success", "Valid Username and

Password") # GUI setup

root = [Link]()

[Link]("Login

Validation")

[Link](root, text="Username").pack()

entry_username = [Link](root)

entry_username.pack()

[Link](root, text="Password").pack()

entry_password = [Link](root, show="*")

entry_password.pack()

[Link](root, text="Validate", command=validate).pack()

[Link]()
OUTPUT:-

CONCLUSION:-

The program effectively demonstrates the practical application of regular expressions (regex)
as a robust mechanism for pattern matching and input validation. By encoding multiple
constraints—such as minimum length, inclusion of uppercase and lowercase characters, digits,
and special symbols—into a single regex pattern, the program ensures that the entered
password adheres to widely accepted security standards. This approach minimizes the risk of
weak credentials and enforces consistency without requiring multiple conditional checks.

From a software design perspective, the use of regex provides a compact and computationally
efficient validation strategy, reducing code complexity while maintaining high reliability. The
validation logic is declarative in nature, meaning the rules are clearly defined within the pattern
itself, making it easier to maintain and extend.

You might also like