0% found this document useful (0 votes)
55 views127 pages

Python Lab Report: Programming Basics

The document is a lab report for an Introduction to Python course at Amrita School of Computing, detailing weekly programming exercises and objectives from installation to advanced topics like web scraping and data visualization. It includes a structured index with specific tasks for each week, covering various Python concepts such as conditional statements, loops, object-oriented programming, regular expressions, and libraries like NumPy and Pandas. The report is submitted by a student and outlines the practical applications of Python programming through hands-on exercises.
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)
55 views127 pages

Python Lab Report: Programming Basics

The document is a lab report for an Introduction to Python course at Amrita School of Computing, detailing weekly programming exercises and objectives from installation to advanced topics like web scraping and data visualization. It includes a structured index with specific tasks for each week, covering various Python concepts such as conditional statements, loops, object-oriented programming, regular expressions, and libraries like NumPy and Pandas. The report is submitted by a student and outlines the practical applications of Python programming through hands-on exercises.
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

INTRODUCTION TO PYTHON

(22AIE205)
LAB REPORT

AMRITA SCHOOL OF COMPUTING,


AMRITA VISHWA VIDYAPEETHAM
AMARAVATI CAMPUS.

Submitted By: Submitted To:


Name: Bonthu Vaasita Name: [Link] Kumar
Roll No: [Link].U4AIE24008 Dept: CSE
Class: AIE-A (2024-2028) Asst. Professor

Signature
Marks
Date

1
Index:
Week Date Programs List Pg No. Marks

WEEK-1 09/07/25 Installation and Basics: 6-10


[Link] of python
[Link] Student details
[Link] input from user and print output
WEEK-2 16/07/25 Conditional Statements: 10-17
1. Write a python code to check the eligibility to vote and
print the message if he is not eligible.
2. Write a python code to grade a student based on marks.
Input marks and display grade
3. Write a python code to find the largest of three numbers.
4. Write a python code to print all even numbers up to N.
5. Write a python code for password checker with Limited
Attempts (3 attempts).
6. Write a python code to find the Factorial of a Number.
7. Write a python code to find the Fibonacci Series up to N
terms.
8. Write a python code to check the number is Armstrong or
not
WEEK-3 23/07/25 Loops: 18-
1. Write a python program to check whether the given
number is Prime Number or not.
2. Write a Python program that calculates the electricity bill
based on the number of units consumed using if, elif, and else
statements.
3. Write a python program for simple ATM Withdrawal
Simulation.
4. Write a python program to create a Menu-Driven
Calculator.
5. Write a python program to create a Login Authentication
System.
6. Write a python program to verify the strength of the
password.
7. Write a python program to generate Dynamic Menu
Navigation.
8. Write a python program to generate the below patterns,
also include the tracing tables.

WEEK-4 30/07/25 Lists and Tuples:


[Link] a program that manages a grocery shopping list. The
program should:
Initialize a list with some grocery items. Add a new item to
the [Link] an item from the [Link] the final shopping
list.
2. Create a program that stores exam scores for students. The
program should:
Initialize a list with scores, Calculate the average score, Find
the highest and lowest scores, Add new scores to the list.
3. Create a program that manages a list of books in a library.
The program should:

2
Initialize with some book titles, Add a new book, Check if a
certain book is available, Remove a book from the list.
4. Create a simple to-do list application that:
Starts with an empty list, Adds tasks, Marks tasks as
completed by removing them, Displays the remaining tasks.
5. You are developing a game that stores the coordinates of
various objects on a grid using tuples.
Add new coordinates, Retrieve coordinates at a specific
index, Count how many times a specific coordinate appears.
6. You need to store fixed configuration options that shouldn't
change during runtime. Create a tuple with configuration
options and try to modify it (which should fail). Then,
convert it to a list, modify, and convert back.
7. You are pairing student names with their IDs using tuples.
Store pairs in a list, Retrieve student ID by name, Count how
many students have IDs greater than 1000.
8. Write a program to display unique vowels present in the
given word?
9. Write a program to filter the words with length greater than
3, using list comprehension.
10. Write a program to flatten a Nested list using list
comprehension.
11. Write a python program to add each element of x list with
each element of y list. Using loops and Using list
comprehension
12. Write a python program to get a list, sorted in increasing
order by the last element in each tuple from a given list of
non-empty tuples..
Week-5 06/08/25 Sets and Dictionary:
1. Write a python program to create a dictionary of weekly
temperatures in our city. The days should be the keys, and the
temperatures (in Celsius) corresponding to the days should be
the values using dictionary comprehension.
2. Write a python program to find all Unique Words from
Multiple Paragraphs.
3. Write a python program using Set Operations for the
course Survey Analysis.
4. Write a python program to find the duplicate elements
from a list.
[Link] a python program to extract all the vowels (Lower or
Upper case letters) from the given sentence.
6. Write a python program to Count how many times each
character appears in a given string using dictionaries.
7. Write a python code to Store student marks and calculate
grade using dictionaries.
8. Write a python program for the below scenario.
Week-6 13/08/25 OOPS:
1. Inheritance – Library Management System
Write a program to create objects of both classes and display
their details.
2. Multiple Inheritance – School System
Write a program to create an object of Student and display the
information.
3. Multilevel Inheritance – Vehicle System
Write a program to display all details of an ElectricCar
object.
4. Polymorphism – Animal Sounds
Write a program to store objects of both classes in a list and
call speak() for each object
5. Operator Overloading – Bank Account

3
Write a program to create two accounts, add them, and print
the result.
6. Abstraction – Payment System
Write a program to create an object of UpiPayment and make
a payment.
7. Encapsulation – Bank Account Access Control
Write a program to create an account, deposit money,
withdraw money, and display the balance.
8. Method Overriding – Employee Work
Write a program that stores objects of each class in a list and
calls work() for each.
9. Real-life Mixed OOP Concepts – Ride Booking App
Write a program to book a CarRide for 10 km.
Week-7 20/08/25 Regex:
1. Write a python program to check whether a given string is
a valid email address.
2. Write a program to Check if a given number is a valid
Indian mobile number (10 digits, starts with 6-9).
3. Write a program to extract all dates in the format dd-mm-
yyyy.
4. Write a program to Extract Hashtags from Social Media
Post ("Learning #Python is fun! #AI #MachineLearning”)
5. write a program to Extract URLs from a given text (Visit
our site at [Link] or follow
[Link]
6. Write a program to mask the credit card number. Replace
all the digits with star(*) except the last four(4) characters.
(Card No - "1234-5678-9876-5432")
7. Write a program to Extract all words starting with a capital
letter from the Text - "Python is Developed by Guido Van
Rossum."
8. Write a regex to extract all PAN card numbers (format: 5
letters + 4 digits + 1 letter.
Week-8 30/08/25 Multiple threading:
1. Write a program that creates a thread to print numbers
from 1 to 5 with a delay of 1 second between each number.
[Link] a program with two threads: one prints numbers (1–
5) and the other prints letters (A–F).
[Link] a program to create a custom-named thread
"SuperThread" and display its name during execution.
Week-9 03/09/25 GUI:
[Link] a python GUI application to create a student
registration form with student details and display them after
successful registration.
[Link] a GUI application to create a calculator, where the
user has to click on the numbers and symbol (Arithmetic
operation). Based on the symbol, it has to display the output.
Week-10 08/10/25 Web Scrapping:
[Link] a Python program using BeautifulSoup to:
i. Fetch the HTML content of a web page
([Link]
[Link] and print the following details:
a. The title text of the page
b. The first paragraph (<p>) on the page

4
c. The first 5 hyperlinks (<a> tags) and their URLs
d. The total number of <a> tags on the page
e. Print the first 300 characters of all visible text on the page.
f. The page title text
g. All the main headings on the page (<h1>, <h2>, and <h3>
tags)
h. The number of <div> tags present on the page
i. All elements with the class name "menu" (print only their
text content)

2. Write a Python program using the requests library to:


i. Send a GET request to the URL
([Link]
ii. Print the following details about the response:
a. The status code (e.g., 200 means success, 404 means not
found)
b. The final URL after redirections (if any)
c. The server type from the response headers
d. The content type
e. The encoding used to decode text
f. The time taken to get the response (in seconds)
g. Whether the request was successful or not (True if status
code < 400)
Week-11 15/10/25 Numpy:
Write Python programs to demonstrate the following NumPy
operations:
1. Creation of arrays
2. array attributes
3. Performing arithmetic operations on NumPy arrays.
4. Performing statistical operations
5. Using aggregate functions
6. Applying trigonometric and mathematical functions.
7. Performing indexing and slicing on arrays.
8. Using logical operations and Boolean indexing.
9. Demonstrating reshaping and flattening of arrays.
10. Demonstrating stacking and splitting of arrays.
Week-12 22/10/25 Pandas nad Data Visualization:
1. Write Python programs to demonstrate the following
Pandas operations:
1. Reading data from a file.
2. Viewing and exploring data using functions such as
head(), tail(), info(), and describe().
3. Selecting and filtering data using labels (loc[]),
integer positions (iloc[]), and conditional filtering.
4. Adding, updating, and deleting columns in a
DataFrame.
5. Handling missing data using isnull(), fillna(), and
dropna().
6. Sorting data using sort_values() .
7. Merging, joining, and concatenating DataFrames.
8. Performing basic statistical operations using built-in
Pandas functions

5
2. Write Python programs to demonstrate the Data
Visualization:
1. Univariate analysis using a histogram ([Link]()) in
Matplotlib.
2. Univariate analysis using a histplot ([Link]()) in
Seaborn.
3. Visualization of categorical variable distribution
using a countplot ([Link]()).
4. Bivariate analysis using a scatter plot ([Link]() or
[Link]()).
5. Comparison of numerical variable distribution
across categories using a boxplot ([Link]()).
6. Multivariate analysis using a pairplot
([Link]()).
7. Visualization of correlations between numerical
variables using a heatmap ([Link]()).
8. Representation of aggregated or summarized data
using a barplot ([Link]()).
9. Saving a plot or visualization using [Link]().

WEEK – 1
[Link] procedure of python IDLE

Aim: To install the Python IDLE in your system

Procedure:
step-1: Go to website [Link]

Step-2: Then we visible the multiple options then click on the Downloads

6
Step 3: Then click on the option windows then you see some of the options then in that click on the stable
updates and download.

Step-4 : Then on the stable releases we have laptop specification based on that click on it then it will start
download.

7
Step-5: After Installation completed then add the path to the environment variable of the system and then we
want to check it.

Step-6: Then it will be complete is in our pc

Output:

8
2. Printing the details of the student using the print stamen in IDLE

Aim: To print the details of the student using print statement in IDLE

Program:

print("Details of student")

name="Vaasita Bonthu"

roll_number="[Link].U4AIE24008"

section="AIE-A"

year="II nd Year"

print("Name :",name)

print("Roll No: ",roll_number)

print("Section :",section)

print("Year :",year)

Output:

Error Table:

S no Error Modification

1 Unterminated Stringn literal (detected at line 2) String should be in between double


Quotes(“ ”)

2 name 'Print' is not defined. Python is case-sensitive , write it in lower


case “print”

Explanation:

1. Print() is function used for displaying output in the console

2. Each print statement prints in next line

3. Python is a case-sensitive language , so write print only in lower-case

9
3)Read the input from the user and display the output in the Idle

Aim: To take the input from the user and display the output given input from the user.

Program:

print('Details of the student')

name=input("Enter the student name: ")

roll_number=int(input(('Enter the roll no: ')))

section=input('Enter the section name: ')

print('Name of the student is: ',name)

print('Roll no: ',roll_number)

print('Section: ',section)

Output:

Error Table:

[Link]. Error Modication

1 name 'Input' is not defined. Python is case-sensitive , write it in lower


case “input”

2 Invalid syntax. Keep “+” in between the string to


concatinate all

Explanation:

1. The function input() is used for taking inputs from the user.

2. By default the user input will be in string format

WEEK – 2
[Link] a python code to check the eligibility to vote and print the message if he is not eligible.

Aim: To check the eligibility to vote and print the message if not eligible

Program:

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

10
if age>=18:

print("you are eligible to vote")

else:

print("you are not eligible to vote")

Output:

Error Table :

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of if , else conditions.
3. Syntax error – missing colon(:) There should be (:) after if and else condition.

Explanation:

[Link](): input of age is taken by the user.

[Link]: the age entered is greater than 18 then it prints the

statements.

[Link]: the if condition is false then the statement is printed.

2. Write a python code to grade a student based on marks. Input marks and display grade:

Grade Rule Grade

90–100 O

85-90 A+

80-85 A

75-80 B+

70–75 B

60–69 C

< 60 Fail

Aim: To grade a student based on marks

Program:

11
per=int(input("Enter the percentage:"))

if per>90 and per<=100:

print("you got O grade")

elif per>85 and per<=90:

print("you got A+ grade")

elif per>80 and per<=85:

print("you got A grade")

elif per>75 and per<=80:

print("you got B+ grade")

elif per>=70 and per<=75:

print("you got B grade")

elif per>=60 and per<=69:

print("you got C grade")

else:

print("you failed in exam")

Output:

Error Table:

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of if , else conditions.
3. Syntax error – missing colon(:) There should be (:) after if , elif and else
condition.
4. Logical error There should be same condition for if , elif i.e.,
per <=90 takes the number 90 so it gives error
for per>=90 in other condition.

Explanation:

1. input() is used to accept percentage from the user.

2. int() is applied to convert string input to an integer.

3. if-elif-else ladder is used to check conditions in sequence.

12
[Link] a python code to find the largest of three numbers.

Aim: To find the largest of three numbers

Program:

a=int(input("Enter a value:"))

b=int(input("Enter b value:"))

c=int(input("Enter c value:"))

if a>b:

if a>c:

print(f'{a} is the greatest among three')

if b>c:

if b>a:

print(f'{b} is the greatest among three')

if c>a:

if c>b:

print(f'{c} is the greatest among three')

Output:

Error Table:

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of if conditions.
3. Syntax error – missing colon(:) There should be (:) after if condition.

Explanation:

1. int(input()): Used to take and convert user input into integers.

2. Three variables a, b, and c store the numbers.

3. Logical operators and and comparison operators > are used to compare values.

4. f-string is used for formatted output — e.g., f"{a} is greatest".

13
[Link] a python code to print all even numbers up to N.

Aim: To print all even numbers unto N(input)

Program:

n=int(input("enter a number:"))

for i in range(n):

if i%2==0:

print(i,end=" ")

Output:

Error Table:

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of for loop conditions.
3. Syntax error – missing colon(:) There should be (:) after for loop condition.
4. Syntax error - range The range should be defined

Explanation:

1. range(n) generates numbers from 0 to n-1.

2. i % 2 == 0 checks if the number is even.

3. print(i, end=" ") prints values on the same line, separated by spaces.

[Link] a python code for password checker with Limited Attempts (3 attempts).

Aim: To check the password with limited attempts (3)

Program:

password='12345'

for i in range(3):

attempt=input("Enter the password:")

if attempt==password:

print("welcome..")

else:

print("wrong password...try again")

Output:

14
Error Table:

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of for loop conditions and if conditions.
3. Syntax error – missing colon(:) There should be (:) after for loop condition and
if conditions.
4. Syntax error - range The range should be defined

Explanation:

1. password = "12345" sets the correct password.

2. while count < 3: allows a maximum of 3 attempts.

3. input() collects user input as a string.

4. if attempt == password: checks correctness.

5. break exits the loop on success.

6. count += 1 increments the number of attempts on failure.

6. Write a python code to find the Factorial of a Number.

Aim: To find the factorial of a number

Program:

n=int(input("Enter a number:"))

factorial=1

for i in range(1,n+1):

factorial*=i

print(factorial)

15
Output:

Error Table:

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of for loop conditions.
3. Undefined factorial Initialize factorial=1 before
4. Syntax error – missing colon(:) There should be (:) after for loop condition.
5. Syntax error - range The range should be defined

Explanation:

1. int(input()) is used to take an integer input from the user.

2. fact = 1 is the initializer for the factorial value.

3. for i in range(1, n + 1) iterates from 1 to n (inclusive).

4. fact = fact * i multiplies the result with each i to compute the factorial.

7. Write a python code to find the Fibonacci Series up to N terms.

Aim: To find the Fibonacci series upto N terms

Program:

print('Vaasita - AIE24008')

n=int(input("Enter number of terms:"))

a=0

b=1

count=0

print("Fibonacci series:")

while count < n:

print(a,end=" ")

a=b

b=a+b

count+=1

Output:

16
Error Table:

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of while loop conditions.
3. a, b, count not defined Initialize a=0 , b=1 and count=0
4. Syntax error – missing colon(:) There should be (:) after for loop condition.

Explanation:

1. Fibonacci Series starts with 0 1, and each number is the sum of the previous two.

2. a and b are initialized to the first two terms (0 and 1).

3. The next term c = a + b is calculated and printed if it is ≤ n.

4. while c <= n: keeps the loop running until the next Fibonacci number exceeds the user-defined limit.

5. print(end=" ") is used to display all values on the same line with spaces.

8. Write a python code to check the number is Armstrong or not

Aim: To check the number is Armstrong or not

Program:

print('Vaasita - AIE24008')

n=int(input("Enter a number:"))

length=len(str(n))

result=sum(int(i)**length for i in str(n))

if n==result:

print("It is armstrong number.")

else:

print("It is not an armstrong number.")

Output:

17
Error Table:

[Link] Error Modification

1. IndentationError: expected an indented Make sure all lines under while and if
block are properly indented

2. not for n-digit numbers It works only for 3 digit numbers

Explanation:

[Link] Number (3-digit): A number is Armstrong if the sum of the cubes of its digits equals the number
itself.

2. n % 10 extracts the last digit of the number.

3. n // 10 removes the last digit (integer division).

4. sum = sum + r³ accumulates the cube of each digit.

WEEK – 3
[Link] a python program to check whether the given number is Prime Number or not.

Aim: To check whether the given number is prime number or not

Program:

print('Vaasita - AIE24008')

n=int(input("Enter a number:"))

if n<=1:

print("not a prime number")

else:

count=0

for i in range(1,n+1):

if n%i==0:

count+=1

if count==2:

18
print("It is a prime number")

else:

print("It is not a prime number")

Output:

Error Table:

[Link] Error Modification

1. ValueError: invalid literal for int() Make sure the input is only numerical

2. IndentationError: expected an indented Make sure all lines under the while and
block if are properly indented

Explanation:

[Link] number: A number is prime if it has exactly 2 factors – 1 and itself.

2. The loop while i <= n checks every number from 1 to n for divisibility.

3. n % i == 0 checks if i is a factor of n.

4. count keeps count of how many numbers divide n.

5. If count == 2, then the number is prime.

[Link] a Python program that calculates the electricity bill based on the number of units consumed using
if, elif, and else statements.

The electricity board charges different rates based on the number of units consumed:

• 0–100 units: ₹1.5 per unit

• 101–200 units: ₹2.5 per unit

• 201–300 units: ₹4.0 per unit

• 301–500 units: ₹6.0 per unit

• Above 500 units: ₹7.5 per unit

Add a fixed surcharge based on the slab:

• ₹25 for ≤100 units

• ₹50 for 101–200 units

19
• ₹75 for 201–300 units

• ₹100 for 301–500 units

• ₹150 for >500 units

Aim: To calculate the electricity bill based on the number of units consumed

Program:

print('Vaasita - AIE24008')

units=int(input("Enter the number of units:"))

if units>=0 and units<=100:

rate=1.5*units

surcharge=25

elif units>=101 and units<=200:

rate=2.5*units

surcharge=50

elif units>=201 and units<=300:

rate=4.0*units

surcharge=75

elif units>=301 and units<=500:

rate=6.0*units

surcharge=100

else:

rate=7.5*units

surcharge=150

bill=rate+surcharge

print("The total bill is:",bill)

Output:

Error Table:

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of if loop conditions.

20
3. Syntax error – missing colon(:) There should be (:) after for loop condition.
4. Runtime Error: rate initialization Define rate and initialize it to 0

Explanation:

[Link] program calculates an electricity bill based on slab-wise units consumed.

2. fixed rate per unit and surcharge is applied based on the range the units fall into.

[Link] amount = units × rate + surcharge.

[Link] a python program for simple ATM Withdrawal Simulation.

Aim: Simple ATM withdrawal simulation

Program:

print('Vaasita - AIE24008')

amt=int(input("Enter the total amount in bank:"))

withdraw=int(input("Enter the amount to withdraw:"))

total_amt=amt-withdraw

print(f"The {withdraw} amount is withdrawn from {amt}")

print("The amount left in the bank is:",total_amt)

Output:

Error Table:

[Link]. Error Modification


1. Logical error: Withdrawal amount > account if withdraw > amt: amount is declared as amt
balance
2. Type Error: '>' not supported between Typecasting for amount and balance is
instances of 'float' and 'str' needed.

Explanation:

[Link]:take input of total amount in the bank from user.

[Link]:take input of the amount need to be withdrawn from user.

[Link] total amount is calculate by subtracting withdraw from amount.

[Link] a python program to create a Menu-Driven Calculator.

21
Aim: To create a Menu-Driven Calculator

Program:

print('Vaasita - AIE24008')

a=int(input("Enter a number:"))

b=int(input("Enter a number:"))

op=input("Enter any operator:")

if op=='+':

s=a+b

elif op=='-':

s=a-b

elif op=='*':

s=a*b

elif op=='/':

s=a/b

print("The operation output is:",s)

Output:

Error Table:

[Link]. Error Modification


1. Indentation error There should be some space for if condition
2. Syntax error:op not defined Operator name should be same for input
and if conditions.

Explanation:

1. The program takes two numbers and an operator as input from the user.

2. It performs the corresponding arithmetic operation (+, -, *, /) given by the user.

5. Write a python program to create a Login Authentication System.

Note: Keeps prompting until correct credentials are entered or attempts are exhausted.

Aim: To create a login authentication system

Program:

print('Vaasita - AIE24008')

22
username="vaasita"

password="12345"

attempt=3

for i in range(attempt):

print("Enter the below details",i+1)

name=input("Enter username:")

pswd=input("Enter the password:")

if name == username and pswd == password:

print("Login Successfull....")

print("Welcome...")

break

elif name != username:

print("Invalid username...Try again.")

i+=1

elif pswd != password:

print("Invalid password...Try again.")

i+=1

if i==attempt:

print("Access denied due to many attempts...")

Output:

Error Table:

23
[Link]. Error Modification
1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of for loop conditions.
3. Syntax error – missing colon(:) There should be (:) after for loop condition.

Explanation:

[Link] username and password are initialised.

[Link] attempts are 3 to enter correct details.

[Link] username if wrong it prints invalid username.

[Link] password is wrong it prints invalid password.

6. Write a python program to verify the strength of the password.

Aim: To verify the strength of the password

Program:

print('Vaasita - AIE24008')

password=input("Enter a paasword:")

if len(password) < 8:

print("week. minimum 8 characters..")

elif([Link]()):

print("strong. entered some letters..")

if([Link]()):

print("space is not allowd..")

elif([Link]()):

print("[Link] some digit..")

else:

print("strongest password...")

Output:

Error Table:

24
[Link]. Error Modification
1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of if loop conditions.
3. Syntax error – missing colon(:) There should be (:) after if loop condition.

Explanation:

[Link] input is taken from the user.

[Link] the length is greater than 8 and have letters along with numbers it gives strongest password.

[Link] not it shows weak password.

7. Write a python program to generate Dynamic Menu Navigation.

Aim: To generate Dynamic Menu Navigation

Program:

print('Vaasita - AIE24008')

while True:

print("\n====== Main Menu ======")

print("1. Home")

print("2. Profile")

print("3. Settings")

print("4. About")

print("5. Help")

print("6. Exit")

choice = input("Enter your choice (1-6): ")

if choice == "1":

print("You selected Home")

elif choice == "2":

print(" You selected Profile")

elif choice == "3":

print("️You selected Settings")

elif choice == "4":

print("️You selected About")

elif choice == "5":

print(" You selected Help")

elif choice == "6":

25
print(" Exiting... Thank you!")

break

else:

print(" Invalid choice. Please enter a number from 1 to 6.")

Output:

Error Table:

[Link]. Error Modification

26
1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of if loop conditions.
3. Syntax error – missing colon(:) There should be (:) after if loop condition.

Explanation:

[Link] is taken from the user to go for menu card.

2. if the user want to go to home he need to click 1.

3. for profile 2 , for settings 3 , for about 4 , for help 5 and for exit press 6.

[Link] prints the corresponding statements.

8. Write a python program to generate the below patterns, also include the tracing tables.

12

123

1234

12345

Aim: To print the given pattern of numbers

Program:

for i in range(1,6):

for j in range(1,i+1):

print(j,end=" ")

print("")

Output:

Tracing Table:

Iteration i value Inner Loop J value in Output of Final printed


range inner loop inner loop output(j)
1 1 Range(1) 0 1 1
2 2 Range(2) 01 12 12
3 3 Range(3) 012 123 123
4 4 Range(4) 0123 1234 1234
5 5 Range(5) 01234 12345 12345

27
Error Table:

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of for loop conditions.
3. Syntax error – missing colon(:) There should be (:) after for loop condition.

Explanation:

1. First for loop prints the number of rows


2. Second for loop prints the number of columns.
3. It prints j value in each row
4. End=” “ : gives the space between the numbers in same row

ii)

Code:
print('Vaasita - AIE24008')
n=5
ascii_char=65
for i in range(n):
for j in range(i+1):
char = chr(ascii_char)
print(char,end="")
ascii_char+=1
print()
Output:

Tracing Table:

Iteration i value Inner Loop J value in Output of Final printed


range inner loop inner loop output(j)
1 1 Range(1) 0 1 A
2 2 Range(2) 01 12 BB
3 3 Range(3) 012 123 CCC
4 4 Range(4) 0123 1234 DDDD
5 5 Range(5) 01234 12345 EEEEE

Error Table:

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements

28
of for loop conditions.
3. Syntax error – missing colon(:) There should be (:) after for loop condition.

Explanation:
1. We usually use 2 loops for pattern printing.
2. We manipulated i,j ranges in such way to get desired pattern

iii)

Code:
print('Vaasita - AIE24008')
n=5
for i in range(n):
for j in range(n-i-1):
print(" ",end="")
for j in range(2*i+1):
print("*",end="")
print()

Output:

Tracing Table:

Iteration i value Inner Loop J value in Output of Final printed


range inner loop inner loop output(j)
1 1 Range(1) 0 1 *
2 2 Range(2) 01 12 ***
3 3 Range(3) 012 123 *****
4 4 Range(4) 0123 1234 *******
5 5 Range(5) 01234 12345 *********

Error Table:

[Link]. Error Modification


1. Name ‘Input()’ is not defined Write it in lower case ‘input()’.
2. Indentation error There should be some space for the statements
of for loop conditions.
3. Syntax error – missing colon(:) There should be (:) after for loop condition.

Explanation:

[Link] usually use 2 loops for pattern printing.

[Link] manipulated i,j ranges in such way to get desired pattern

29
Week-4

1. Create a program that manages a grocery shopping list. The program should:

• Initialize a list with some grocery items.


• Add a new item to the list.
• Remove an item from the list.
• Print the final shopping list.
Aim: To manage a grocery shopping list by adding and removing items.
Program:
print('Vaasita - AIE24008')
grocery=['rice','coffee','oil','salt','mangoes']
[Link](['milk','corn flour','wheat flour'])
print("after adding grocery items:",grocery)
[Link]('wheat flour')
print("after removing grocery item:",grocery)
print("the final grocery shoping list is:",grocery)
Output:

Error Table:

[Link]. Error Modification


1. Syntax error: ] was never closed. [ ] should be closed.

Explanation:
[Link] a list consists grocery items.
[Link] attribute is used to add some more grocery items to the list.
[Link] attribute is used to remove an item from the list.
4. print the final grocery list.

2. Create a program that stores exam scores for students. The program should:
• Initialize a list with scores.
• Calculate the average score.
• Find the highest and lowest scores.
• Add new scores to the list.
Aim: To store exam scores of students.
Program:
print('Vaasita - AIE24008')
scores=[99,76,89,95,86]
print("Scores:",scores)
average=sum(scores) / len(scores)
print("Average:",average)
high_score=scores[0]
low_score=scores[0]
for v in scores:
if v<low_score:
low_score=v
if v>high_score:
high_score=v

30
print("Minimum value is:", low_score)
print("Maximum value is:", high_score)
[Link]([94,88,80,72,79])
print("After adding scores:",scores)
Output:

Error Table:

[Link]. Error Modification


1. Indentation error There should be space for the if condition
-statement
2. Syntax error : perhaps forgot comma There should be a comma after double
quotes in print statement.
3. Type Error: unsupported operand type There should not be (‘‘)
for ‘int’ For int values in the list

Explanation:
[Link] a list consisting of scores.
[Link] average of the scores.
[Link] the maximum and minimum scores using loop statements.
4. extend attribute is used to add new scores to the list.
[Link] the final list of scores.

3. Create a program that manages a list of books in a library. The program should:
• Initialize with some book titles.
• Add a new book.
• Check if a certain book is available.
• Remove a book from the list.
Aim: To manage a list of books in a library.
Program:
print('Vaasita - AIE24008')
books=['Wings of fire','The Secret','You Can Win','Ikigai']
print("Books:",books)
[Link]('Atomic Habits')
print("After adding new book:",books)
check=input("Enter a book :")
if check in books:
print("Book is available..")
else:
print("Book is not available..")
[Link]('The Secret')
print("After removing books",books)
Output:

31
Error Table:

[Link]. Error Modification


1. Indentation errror There should be some space after loop
condition.
2. Syntax error : ‘:’ missing There should be : after condition.

Explanation:
[Link] a list consists of title of books.
[Link] attribute is used to add a book to list.
Check if the book is available or not using if-else conditions.
[Link] attribute used to remove a book from the list.
4. print the list of books.

4. Create a simple to-do list application that:


• Starts with an empty list.
• Adds tasks.
• Marks tasks as completed by removing them.
• Displays the remaining tasks.
Aim: To create a simple to-do list application.
Program:
print('Vaasita - AIE24008')
todo_list = []

while True:
print("\n------- To-Do List --------")
print("1. Add Task")
print("2. Complete Task (Remove)")
print("3. Display Tasks")
print("4. Exit")

choice = input("Enter your choice (1-4): ")

if choice == '1':
print("--- You chose to add a task ---")
task = input("Enter the task to complete: ")
if [Link]() in [[Link]() for t in todo_list]:
print("You already added this task before..")
else:

32
todo_list.append(task)
print("Task added successfully.")

elif choice == '2':


print("--- You chose to remove a completed task ---")
if not todo_list:
print("No tasks to complete.")
else:
task = input("Enter the task to remove: ")
found = False
for t in todo_list:
if [Link]() == [Link]():
todo_list.remove(t)
print(f"{task} completed and removed.")
found = True
break
if not found:
print("Task not found in the list.")

elif choice == '3':


print("--- Displaying To-Do List ---")
if not todo_list:
print("Your to-do list is empty.")
else:
for i, task in enumerate(todo_list, start=1):
print(f"{i}. {task}")

elif choice == '4':


print("Exiting the To-Do list app. Goodbye!")
break

else:
print("Invalid choice. Please enter a number from 1 to 4.")
Output:

33
Error Table:

[Link]. Error Modification


1. Syntax error: ‘[‘ was never closed Close [ ] in list_coordinates
2. Syntax error:’)’ was missing Close ( ) while using it in tuples

Explanation:
1. initialize a to-do list.
2. Using while loop enter the number according to the menu.
3. If you choose 1: add a task , for 2 remove the completed task , for 3 display the task , for 4 exit the
loop.

5. You are developing a game that stores the coordinates of various objects on a grid using tuples.
Task:
Create a list of coordinate tuples. Write functions to:
• Add new coordinates.
• Retrieve coordinates at a specific index.
• Count how many times a specific coordinate appears.
Aim: To develop a game that stores the coordinates of various objects on a grid using tuples.
Program:
print('Vaasita - AIE24008')
list_coordinates=[(1,2),(3,4),(5,6)]
print("List of coordinates:",list_coordinates)
list_coordinates.append((3,7))
print("After adding new coordinates:", end=" ")
print(list_coordinates)
print("Coordinates at Index 3:",list_coordinates[3])
print("Coordinates at Index 1:",list_coordinates[1])
print("Count of (5,6):",list_coordinates.count((5,6)))

34
Output:

Error Table:

[Link]. Error Modification


1. Syntax error: ‘[‘ was never closed Close [ ] in list_coordinates
2. Syntax error:’)’ was missing Close ( ) while using it in tuples

Explanation:
[Link] is defined using tuple.
[Link] is used to add new coordinates.
[Link] the list and indexes and count of the coordinate.

6. You need to store fixed configuration options that shouldn't change during runtime.
Task:
Create a tuple with configuration options and try to modify it (which should fail).
Then, convert it to a list, modify, and convert back.
Aim: To store fixed configure options and convert it into list.
Program:
print('Vaasita - AIE24008')
configuration=[('Light-mode'),('Language'),('Notifications'),('Help')]
print("configuration options:",configuration)
config = list(configuration)
[Link]('Close-Tab')
[Link]('Notifications')
config_option = tuple(config)
print("Converted to list,modified,converted to tuple")
print(config_option)
Output:

Error Table:

[Link]. Error Modification


1. Syntax error: notifications not found to Due to case sensitive it is Notifications.
remove.
2. List has no attribute rmove. Typing error it is remove.

Explanation:
1. define configuration options using tuple and convert into list.
2. Using append to add options and remove to remove the options.
3. Convert the list into tuple.

35
7. You are pairing student names with their IDs using tuples.
Task:
• Store pairs in a list.
• Retrieve student ID by name.
• Count how many students have IDs greater than 1000.
Aim: To make a list of students and their IDs and count how many have Ids greater than 1000.
Program:
print('Vaasita - AIE24008')
students=[('abc',980),('def',1067),('ghi',1120),('jkl',870),('mno',1234),('pqr',1133)]
print("The names and IDs of students are:",students)
pairs=list(students)
name=input("Enter the name of a student:")
for student in students:
if student[0] == name:
print(f"{name}'s ID is: {student[1]}")
found = True
break

if not found:
print("Student not found.")

count = 0
for student in students:
if student[1] > 1000:
count += 1
print("Number of students with id greater than 1000 are:",count)
Output:

Error Table:

[Link]. Error Modification


1. Syntax error: perhaps you forgot comma. There should be a comma after the print
statement to print the value of a attribute.

Explanation:
1. A list of tuples stores student names and their corresponding IDs.
2. The user enters a name, and the code searches the list to find the matching ID.
3. If found, the student ID is displayed; if not, a message is shown.
4. Then it counts and prints how many students have IDs greater than 1000 using a loop.

8. Write a program to display unique vowels present in the given word?


Aim: To display unique vowels in given word.
Program:
print('Vaasita - AIE24008')
word=input("Enter a word: ").lower()
vowels=['a','e','i','o','u']
vowels_word=[]
for letter in word:
if letter in vowels:

36
if letter not in vowels_word:
vowels_word.append(letter)
print("the vowels in the word:",vowels_word)

Output:

Error Table:

[Link]. Error Modification


1. Syntax error: <str> value in vowels There should be ‘ ‘ for string values.
2. Indentation error There should be some space after loop
conditions.

Explanation:
[Link] input of a wo5rd from the user and convert into lower case letters.
[Link] vowels with list and vowels in word as a list
[Link] for loop the letter in the word and using if condition check the letter in vowels I or not .
[Link] the letter in vowels add the letter to list of vowels in word and print the letters.

9. Write a program to filter the words with length greater than 3, using list comprehension.
Aim: To filter the words with length greater than 3 using
list comprehension.
Program:
print('Vaasita - AIE24008')
text = input("Enter a sentence: ")
words = [Link]()
filtered_words = [i for i in words if len(i) > 3]
print("Words with length greater than 3:", filtered_words)
Output:

Error Table:

[Link]. Error Modification


1. Syntax error: no attribute length For length of word the attribute is len.
2. Words not defined The initialisation given is filtered_words.

Explanation:
[Link] input from the user to enter a sentence.
[Link] each word in sentence given by user.
[Link] for loop check the length of each word.
[Link] the words length greater than 3.

37
10. Write a program to flatten a Nested list using list comprehension.
Aim: To flatten a nested list using list comprehension.
Program:
print('Vaasita - AIE24008')
nested_list = [[1,2,3],[4,5],[6],[7,8,9]]
print("Nested List:",nested_list)
flattened_list = [item for sublist in nested_list for item in sublist]
print("Flattened list:", flattened_list)
Output:

Error Table:

[Link]. Error Modification


1. Syntax error:’[’ was nrever closed Close [ ] after completion of list.
2. Syntax error : perhaps forgot comma There should be a comma after double
quotes in print statement.

Explanation:
1. A nested list of integers is defined.
2. List comprehension is used to iterate through each sublist and item.
3. The result is a flattened single list of all numbers.
[Link] the output.

11. Write a python program to add each element of list x with list y using nested loops.
Test case x y Result
TESTCASE-1 [10,20,30] [1,2,3,4] 11
12
13
14
21
22
23
24
31
32
33
34

Aim: To add each element of list using nested loop.


Program:
print('Vaasita - AIE24008')
x = [10, 20, 30]
y = [1, 2, 3, 4]

print("Result:")
for i in x:
for j in y:

38
print(i + j)
Output:

Error Table:

[Link]. Error Modification


1. Indentation error Space after the loop.
2. Syntax error:perhaps fergot : There should be : after the loop condition

Testcase:

Testcases Values of x Values of y Result


Testcase - 1 [10,20,30] [1,2,3,4]
10 1 11
10 2 12
10 3 13
10 4 14
20 1 21
20 2 22
20 3 23
20 4 24
30 1 31
30 2 32
30 3 33
30 4 34

Explanation:
[Link] x and y lists.
[Link] for loop add the elements of x to y.
Outer loop for elements of x
Inner loop for elements of y
Add the elements.
3. print the output.

12. Write a python program to add each element of x list with each element of y list.
a) Using loops
b) Using list comprehension
Test case X y Result
TESTCASE-1 [1,2,3,4] [5,6,7,8] [6,8,10,12]
TESTCASE-2 [0,3,4,5] [7,3,2,5]
Aim: To add each element of list x to list y.
Program:
print('Vaasita - AIE24008')

39
x = list(map(int, input("Enter numbers for list x: ").split()))
y = list(map(int, input("Enter numbers for list y: ").split()))
result = []

if len(x) == len(y):
for i in range(len(x)):
[Link](x[i] + y[i])
print("Result using loop:", result)
else:
print("Lists must be of same length.")
Output:

Error Table:

[Link]. Error Modification


1. Result not defined Initialize result as empty list.

Testcase:

Testcases Value of x Value of y Result


Testcase – 1 [1,2,3,4] [5,6,7,8] [6,8,10,12]
Testcase - 2 [0,3,4,5] [7,3,2,5] [7,6,6,10]

Explanation:
1. The code first uses a for loop to add elements from two lists x and y index-wise.
2. Then it uses list comprehension to do the same in one line.
3. It prints both resulting lists

13. Write a python program to get a list, sorted in increasing order by the last element in each tuple
from a given list of non-empty tuples..

testcase input result


1 [(1,5,3) ), (2, 2, 1), (3, 1, 4)] [(2, 2, 1), (1, 5, 3), (3, 1,
4)]
2 ((100, 50, 13), (2, 2, 10), (30, 1, 4)) [(30, 1, 4), (2, 2, 10), (100, 50, 13)]

Aim: To get a list sorted in increasing order by the last element in each tuple

Program:
print('Vaasita - AIE24008')
x = [(1,5,3),(2,2,1),(3,1,4)]
x_sort = sorted(x,key=lambda x:x[-1])
print("After sorting TestCase-1")
print(x_sort)
y = [(100,50,13),(2,2,10),(30,1,4)]

40
y_sort = sorted(y,key=lambda y:y[-1])
print("After sorting TestCase-2")
print(y_sort)
Output:

Error Table:

[Link]. Error Modification


1. Syntax error:)was never closing. Close ) after the statement.

Explanation:
1. Lambda Function: lambda x: x[-1] returns the last element of each tuple.
2. sorted(): Sorts the list of tuples based on this last element.
3. Test Case 1 Output: [(2, 2, 1), (1, 5, 3), (3, 1, 4)]
4. Test Case 2 Output: [(30, 1, 4), (2, 2, 10), (100, 50, 13)]

WEEK – 5

[Link] a python program to create a dictionary of weekly temperatures in our city. The days
should be the keys, and the temperatures (in Celsius) corresponding to the days should be the
values using dictionary comprehension.

Aim: To create a dictionary of weekly temperatures.

Program:

print("Vaasita - AIE24008")

days=['sunday','monday','tuesday','wednesday','thursday','friday','saturday']

temperature=[43,34,35,38,40,37,41]

weekly_temp={day:temp for day,temp in zip(days,temperature)}

print("Weekly temperatures:",weekly_temp)

Output:

Error table:

[Link]. Error Modification


1. Syntax error – missing ‘ ‘ is never [Link] the colon.

Explanation:

[Link] a dictionary of days and their temperatures.

41
[Link] for and zip make a dictionary for each day each temperature.

[Link] the weekly temperature dictionary.

[Link] a python program to find all Unique Words from Multiple Paragraphs.

Aim: To find unique words from multiple paragraphs.

Program:

print("Vaasita - AIE24008")

sentence1=['This is vaasita studying ,'

'in Amrita vishwa vidhyapeetham,'

'persuing Btech in AIE.']

sentence2=['currently iam in 3rd semister learning python.'

' pyhton is a high level programming language.'

'python is known for its simplicity,readability, and community support']

p1 = "".join(sentence1)

p2 = "".join(sentence2)

l1=[Link]()

l2=[Link]()

unique_words=set(l1+l2)

print("Unique words :")

print(unique_words)

print("Total unique words: ",len(unique_words))

Output:

Error table:

42
[Link]. Error Modification
1. Syntax error – missing ‘ ‘ is never [Link] the colon.
2. Syntax error – space not required Space not required for .join

Explanation:

[Link] the lines in the paragraph using “”.join

[Link] the words in the paragraph using .split

[Link] both the sets.

[Link] unique words.

3. Write a python program using Set Operations for the course Survey Analysis.
Task: Perform union, intersection, and symmetric difference.

Aim: To perform set operations for the course survey analysis.

Program:

print("Vaasita - AIE24008")

set1={'abc','def','ghi','vw','xyz'}

set2={'mno','abc','vw','xyz'}

union_set = [Link](set2)

print("Union of Set1 and Set2:", union_set)

intersection_set = [Link](set2)

print("Intersection of Set1 and Set2:", intersection_set)

difference_set = [Link](set2)

print("Difference (Set1 - Set2):", difference_set)

Output:

Error table:

[Link]. Error Modification

1. Logical Error: Remember set operations are case-sensitive —


normalize with .lower() or .upper() if needed
For checking of the subject then we used for the
two sets then we will get error

43
Explanation:

[Link] automatically remove duplicates and store items in no particular order.


[Link]():Combines all unique elements from both sets
[Link]():Returns elements common to both sets.
[Link]():Items in course_1 not in course_2 so it will remove common elements

4. Write a python program to find the duplicate elements from a list.


Note: use for loops and set().

Aim: To find the duplicate element from a list.

Program:

print("Vaasita - AIE24008")

original = [2,2,3,4,5,5,3,6,1,8,2,3,6,0,9,8,9]

unique = []

for item in original:

if item not in unique:

[Link](item)

print("Original List:", original)

print("List after removing duplicates:", unique)

Output:

Error table:

[Link]. Error Modification


1. Syntax error – missing ‘ ‘ is never [Link] the colon.
2. uplicate = [] then [Link](i)'list' object add() is for sets — use append() for lists or use
has no attribute 'add' a set from the start

Explanation:

1.A set named duplicate is used to store only unique duplicate values.
[Link] i in list1: loops through each element in the list.
[Link](i) > 1 checks if the element appears more than once.
[Link] it does, it is added to the duplicate set.
[Link] a set ensures that each duplicate appears only once in the result.

[Link] a python program to extract all the vowels (Lower or Upper case letters) from the given
sentence.

Aim: To extract all vowels from the given sentence.

44
Program:

print("Vaasita - AIE24008")

print("Enter a sentence:")

sentence=input()

vowels=['a','e','i','o','u','A','E','I','O','U']

vowels_sentence=[]

for letter in sentence:

if letter in vowels:

vowels_sentence.append(letter)

print("the vowels in the sentence are : ")

print(vowels_sentence)

Output:

Error table:

[Link]. Error Modification


1. Indent Error Expected indent after if Give proper indentations
statements
Explanation:

[Link] program starts with a predefined list L that contains duplicate numbers.
[Link] creates an empty set named s to store unique elements.
3.A for loop iterates through each item in the list L.
[Link] the loop, each item is added to the sets using the .add() method.
[Link] sets only store unique items, duplicates are automatically ignored.

6. Write a python program to Count how many times each character appears in a given string
using dictionaries.

Aim: To count how many times each character appears in a given string.

Program:

print("Vaasita - AIE24008")

string=input("Enter a string:")

count={}

for char in string:

if char in count:

45
count[char]+=1

else:

count[char]=1

print("Charecter Count:")

for char,num in [Link]():

print(f"{char}:{num}")

Output:

Error table:

[Link]. Error Modification


1. Syntax error – missing “ ‘”is never [Link] the colon.
2. Indent Error Expected indent after if Give proper indentations
statements

Explanation:

[Link] program uses a dictionary to count how many times each character appears in a string.
[Link] iterates through each char in the user-provided string.
[Link] the char is already a key in the dictionary, its value (the count) is incremented by 1.
[Link] the char is not yet in the dictionary, it's added as a new key with a starting value of 1.

7. Write a python code to Store student marks and calculate grade using dictionaries.

Aim: To store students marks and calculate grade using dictionaries.

Program:

print("Vaasita - AIE24008")

marks={'abc': 89, 'def': 94, 'xyz': 99, 'pqr': 81}

def grade(score):

if score>=90:

return 'O'

elif score>=80:

46
return 'A'

elif score>=70:

return 'B'

elif score>=60:

return 'C'

elif score>=50:

return 'D'

elif score>=40:

return 'E'

else:

return 'F'

for name, score in [Link]():

student_grade=grade(score)

print(f"{name} \t{score} \t{student_grade}")

Output:

Error table:

[Link]. Error Modification


1. Syntax error – missing : There should be a colon(:) after if condition.

Explanation:

8. Write a python program for the below scenario.


Scenario: You are managing a small bookstore’s inventory.
Task: Update quantity and add/remove items.

Aim: To manage a small bookstore inventory.

Program:

print("Vaasita - AIE24008")

inventory = {

'Python Basics': 10,

'Data Structures': 5,

'AI for Beginners': 7

47
}

while True:

print("\n1. View Inventory")

print("2. Add Book")

print("3. Remove Book")

print("4. Update Quantity")

print("5. Exit")

choice = input("Choose an option (1-5): ")

if choice == '1':

print("\nInventory:")

for book, qty in [Link]():

print(book, ":", qty)

elif choice == '2':

book = input("Enter book name to add: ")

qty = int(input("Enter quantity: "))

inventory[book] = qty

print("Book added.")

elif choice == '3':

book = input("Enter book name to remove: ")

if book in inventory:

del inventory[book]

print("Book removed.")

else:

print("Book not found.")

elif choice == '4':

book = input("Enter book name to update: ")

if book in inventory:

qty = int(input("Enter new quantity: "))

inventory[book] = qty

print("Quantity updated.")

else:

print("Book not found.")

elif choice == '5':

48
print("Goodbye!")

break

else:

print("Invalid choice.")

Output:

49
Error table:

[Link]. Error Modification


1. Syntax error – missing : There should be colon after if condition.(:)
2. uplicate = [] then [Link](i)'list' object add() is for sets — use append() for lists or use
has no attribute 'add' a set from the start

Explanation:

[Link] program simulates a bookstore's inventory using a dictionary, where keys are book titles and
values are their quantities.
2.A while True loop creates a continuous menu-driven interface for the user.
[Link] user can choose to view inventory, add a book, update a quantity, remove a book, or exit .
[Link] input is handled with if-elif-else conditions to perform the chosen action on the inventory
dictionary .

9. Write a python code to concatenate three dictionaries into one.

Aim: To concatenate three dictionaries into one.

Program:

print("Vaasita - AIE24008")

dict1={1:'a',2:'b',3:'c'}

dict2={4:'e',5:'f',6:'g'}

dict3={7:'h',8:'i',9:'j'}

concatenated={**dict1, **dict2, **dict3}

print("Concatenated Dictionary:",concatenated)

Output:

Error table:

[Link]. Error Modification


1. Syntax error – missing ‘ ‘ is never [Link] the colon.

Explanation:

[Link] program starts with three separate dictionaries: dict1, dict2, and dict3 .

[Link] uses the dictionary unpacking operator (**) to merge them.

[Link] syntax {**dict1, **dict2, **dict3} creates a new dictionary by combining all key-value pairs
from the three source dictionaries into one.

50
10. Write a python code to swap keys and values in a dictionary. Assume all values are unique.

Aim: To swap keys and values in a dictionary.

Program:

print("Vaasita - AIE24008")

original_dict = {"V": 1, "A": 2, "S": 3, "I": 4,"T":5}

swapped_dict = {}

for k, v in original_dict.items():

swapped_dict[v] = k

print("Original Dict:",original_dict)

print("Swapped Dict:",swapped_dict)

Output:

Error table:

[Link]. Error Modification


1. Syntax error – missing “ “ is never [Link] the colon.

Explanation:

1. This program assumes that all values in the original dictionary are unique.
2. It initiates a new dictionary to store swapped results.
3. It iterates through the original dictionary.
4. For each pair it assigns the value as the key and the key as the new value.

Week – 6

1. Inheritance – Library Management System

AIM: Create a base class LibraryItem with attributes title and item_id, and a method display_info().

Derive two classes:

• Book (with an extra attribute author)

• Magazine (with an extra attribute issue_no).

Override the display_info() method in both child classes to include their additional attributes.

Task: Write a program to create objects of both classes and display their details.

Aim: To create a base library item with attributes.

51
Program:

print("Vaasita - AIE24008")

print()

class libraryitem:

def __init__(self,title,item_id):

[Link]=title

self.item_id=item_id

def display_info(self):

print(f"Title: {[Link]}")

print(f"ID of Item: {self.item_id}")

class book(libraryitem):

def __init__(self,title,item_id,author):

super().__init__(title,item_id)

[Link]=author

def display_info(self):

super().display_info()

print(f"Author: {[Link]}")

class magazine(libraryitem):

def __init__(self,title,item_id,issue_no):

super().__init__(title,item_id)

self.isuue_no=issue_no

def display_info(self):

super().display_info()

print(f"Issue No.: {self.isuue_no}")

book1=book("Atomic Habits",29,"James Clear")

magazine1=magazine("National Geographic",44,102234)

52
book1.display_info()

print()

magazine1.display_info()

Output:

Error table:

[Link]. Error Modification


1. Type error: book.__init__() takes 2 positional Give only 2 arguments not 4.
arguments but 4 were given
2. AttributeError: 'book' object has no attribute Add title attribute in book class.
'title'

Explanation:

[Link] a class library, and initialize title and item id in parent class(libraryitem).

[Link] a class book and initialize the author by calling the parent class in child class.

[Link] a magazine class and initialize the issue no. by calling the parent class in child class.

[Link] objects for book class and magazine class , and then display by calling the display_info.

2. Multiple Inheritance – School System

AIM: Create two parent classes:

• Person (with name)

• StudentRecord (with roll_no)

Create a child class Student that inherits from both and has a method to display student details.

Task: Write a program to create an object of Student and display the information.

Aim: To create a child class student and method to display student details.

Program:

print("Vaasita - AIE24008")

print()

class person:

def __init__(self,name):

53
[Link]=name

def display(self):

print(f"Student's Name: {[Link]}")

class studentrecord:

def __init__(self,roll):

[Link]=roll

def display_roll(self):

print(f"Roll No.: {[Link]}")

class student(person,studentrecord):

def __init__(self, name, roll):

person.__init__(self, name)

studentrecord.__init__(self, roll)

s1=student("vaasita",24008)

[Link]()

s1.display_roll()

Output:

Error table:

[Link]. Error Modification


1. TypeError: person.__init__() missing 1 Value for name argument should be given in
required positional argument: 'name'. person.
2. AttributeError: 'student' object has no attribute To display the attribute is display not person.
'person'.

Explanation:

[Link] a class person define attribute name and display()-used to display the attribute value.

[Link] a class studentrecord define roll no. and display_roll()-used to display roll no.

[Link] a child class that inherits parent class (person , studentrecord) attributes.

54
[Link] an object of student and display the information.

3. Multilevel Inheritance – Vehicle System

AIM:

Create a base class Vehicle with an attribute brand.

Create a child class Car with an attribute fuel_type.

Create a subclass ElectricCar that inherits from Car and has an attribute battery_capacity.

Task: Write a program to display all details of an ElectricCar object.

Aim: To display all details of an electric car object.

Program:

print("Vaasita - AIE24008")

print()

class vehicle:

def __init__(self,brand):

[Link]=brand

def display_brand(self):

print(f"Brand: {[Link]}")

class car(vehicle):

def __init__(self,brand,fuel):

super().__init__(brand)

[Link]=fuel

def display_fuel(self):

print(f"Fuel type: {[Link]}")

class electriccar(car):

def __init__(self,brand,fuel,battery):

super().__init__(brand,fuel)

[Link]=battery

def display(self):

print(f"Battery capacity: {[Link]}")

55
car1=electriccar("BMW","petrol","81.6KW/h")

car1.display_brand()

car1.display_fuel()

[Link]()

Output:

Error table:

[Link]. Error Modification


1. TypeError: person.__init__() missing 1 Value for brand argument should be given in
required positional argument: 'brand'. class -vehicle.

Explanation:

[Link] a class vehicle. Define brand attribute and display function.

[Link] a child class car. Define fuel no. attribute and display [Link]()- call parent attribute.

[Link] a child class electriccar that inherits car attributes . Define battery attribute and display function.

[Link] an object electric car and display the details.

4. Polymorphism – Animal Sounds

AIM:

Create a base class Animal with an abstract method speak().

Create subclasses Dog and Cat that override speak() to print appropriate sounds.

Task: Write a program to store objects of both classes in a list and call speak() for each object

Aim: To store objects of both classes in a list and call speak for object.

Program:

print("Vaasita - AIE24008")

print()

class animal:

def speak(self):

print("Animal makes different sounds")

class dog(animal):

56
def speak(Self):

print("Dog barks")

class cat(animal):

def speak(self):

print("Cat meows")

animals=[animal(),dog(),cat()]

for animal1 in animals:

[Link]()

Output:

Error table:

[Link]. Error Modification


1. TypeError: vehicle.__init__() missing 1 Value for brand argument should be given in
required positional argument: 'brand'. class -vehicle.

Explanation:

[Link] a animal class . dog and cat classes inherit from animal class.

[Link] and cat subclasses inherits speak() method but define on its own method.

[Link] and cat classes override the speak() method of animal.

[Link] an object of animal and make a list of all the classes.

[Link] for loop print the method according to the classes.

5. Operator Overloading – Bank Account

AIM:

Create a class BankAccount with an attribute balance.

Overload the + operator so that adding two accounts returns a new account with the combined balance.

Task: Write a program to create two accounts, add them, and print the result.

Aim: To create two accounts add them and print the result.

57
Program:

print("Vaasita - AIE24008")

print()

class bankaccount:

def __init__(self,balance):

[Link]=balance

def __add__(self,other):

return([Link]+[Link])

def __str__(self):

return f"Balance: ₹{[Link]}"

acc1=bankaccount(5000)

acc2=bankaccount(10000)

balance=acc1+acc2

print("balence in account 1: ",acc1)

print("balence in account 2: ",acc2)

print("total balence: ",balance)

Output:

Error table:

[Link]. Error Modification


1. AttributeError: 'bankaccount' object has no Typo error instead of balance write balance.
attribute 'balance'. Did you mean: 'balence'?

Explanation:

[Link] a class bankaccount with a balance attribute.

2. Overloads the + operator so you can add two bankaccount objects directly.

[Link] to the sum of bank balences

[Link] 2 accounts with balance . add them and print the balance.

6. Abstraction – Payment System

58
AIM:

Using the abc module, create an abstract class Payment with an abstract method
make_payment(amount).

Create subclasses:

• CreditCardPayment

• UpiPayment

Implement the method to print payment details.

Task: Write a program to create an object of UpiPayment and make a payment.

Aim: To create an object of UPI Payment and make a payment.

Program:

print("Vaasita - AIE24008")

print()

from abc import ABC,abstractmethod

class Payment(ABC):

@abstractmethod

def make_payment(self, amount):

pass

class CreditCardPayment(Payment):

def make_payment(self, amount):

print(f"Paid ₹{amount} using Credit Card.")

class UpiPayment(Payment):

def make_payment(self, amount):

print(f"Paid ₹{amount} using UPI.")

if __name__ == "__main__":

payment_method = UpiPayment()

payment_method.make_payment(1500)

Output:

Error table:

[Link]. Error Modification


1. TypeError: payment.__init__() missing 1 Value for amount argument should be given in
required positional argument: 'brand'. class -payment.

59
Explanation:

[Link] the abstraction tool.

[Link] the abstract class payment.

[Link] a subclass creditcardpayment that inherits payment class and overrides make_payment.

[Link] another subclass upipayment that inherits payment class and overrides make_payment.and ptint the
output by the object.

7. Encapsulation – Bank Account Access Control

AIM:

Create a class BankAccount with a private attribute __balance.

Add methods:

• deposit(amount)

• withdraw(amount)

• get_balance()

Ensure that withdrawals cannot exceed the available balance.

Task: Write a program to create an account, deposit money, withdraw money, and display the balance.

Aim: To create an account deposit , withdraw , money and display balance.

Program:

print("Vaasita - AIE24008")

print()

class BankAccount:

def __init__(self, balance=0):

self.__balance = balance

def deposit(self, amount):

if amount > 0:

self.__balance += amount

print(f"Deposited: ₹{amount}")

else:

print("Deposit amount must be positive.")

def withdraw(self, amount):

60
if amount <= self.__balance:

self.__balance -= amount

print(f"Withdrew: ₹{amount}")

else:

print("Insufficient balance!")

def get_balance(self):

return self.__balance

if __name__ == "__main__":

account = BankAccount(5000)

[Link](2000)

[Link](1000)

[Link](7000)

print("Current Balance: ₹", account.get_balance())

Output:

Error table:

[Link]. Error Modification


1. TypeError: [Link]() takes 0 There should be an argument (self).
positional arguments but 1 was given

Explanation:

[Link] the class bankaccount with the balance attribute.

[Link] deposit with the amount attribute.

[Link] withdraw with the amount attribute that overrides.

[Link] get balance to implement the print statement to print the remaining balance in the account.

8. Method Overriding – Employee Work

AIM:

Create a base class Employee with a method work().

Create subclasses:

61
• Developer (overrides work() to print "Developer writes code")

• Manager (overrides work() to print "Manager manages team")

Task: Write a program that stores objects of each class in a list and calls work() for each.

Aim: To store objects of each class in a list calls work() for each.

Program:

print("Vaasita - AIE24008")

print()

class employee:

def work(self):

print("Employee works in office from 9 to 5")

class developer(employee):

def work(self):

print("Developer writes code")

class manager(employee):

def work(self):

print("Manager manages the team")

employees=[employee(),developer(),manager()]

for emp in employees:

[Link]()

Output:

Error table:

[Link]. Error Modification


1. TypeError: [Link]() takes 0 There should be an argument
positional arguments but 1 was given (self).

Explanation:

[Link] a class employee and define work and print employee work time.

[Link] a class developer that inherits from employee class and overrides the work method.

[Link] another class manager that inherits from class employee and overrides work method.

62
[Link] a list of the class and create an object to print .

9. Real-life Mixed OOP Concepts – Ride Booking App

AIM:

Using the abc module, create an abstract class Ride with an abstract method calculate_fare(distance).

Create subclasses:

• CarRide (fare = distance × 15)

• BikeRide (fare = distance × 8)

Create a Booking class that takes a Ride object and a distance, and has a method confirm_booking() to
display the fare.

Task: Write a program to book a CarRide for 10 km.

Aim: To create a booking class that takes ride object and a distance and method confirm booking to display the
fare.

Program:

print("Vaasita - AIE24008")

print()

from abc import ABC,abstractmethod

class ride(ABC):

@abstractmethod

def calculate_fare(self,distance):

[Link]=distance

pass

class carride(ride):

def calculate_fare(self,distance):

return distance*15

class bikeride(ride):

def calculate_fare(self,distance):

return distance*8

class booking:

def __init__(self,ride,distance):

[Link]=ride

[Link]=distance

def confirm(self):

fare = [Link].calculate_fare([Link])

63
print(f"distance: {[Link]}")

print(f"fare: {fare}")

if __name__ == "__main__":

ride=carride()

booking=booking(ride,10)

[Link]()

Output:

Error table:

[Link]. Error Modification


1. 'booking' object has no attribute 'self' It is confirm not self.
2. NameError: name 'fare' is not defined Define fare .

Explanation:

[Link] abstract method.

[Link] an abc class ride with distance attribute.

[Link] a subclass carried that inherits ride.

[Link] a subclass bikeride that inherits ride.

[Link] a booking class that has init constructor and confirm method.

[Link] an object for carried and booking and call confirm method to print the output.

WEEK – 7

[Link] a python program to check whether a given string is a valid email address.

Aim: To check whether a given string is valid email address.

Program:

print("Vaasita - AIE24008")

print()

import re

string=input("Enter an email: ")

email=[Link](r'^[a-z0-9]+@gmail\.com$', string)

if email:

print("Valid Email..")

64
else:

print("Invalid Email..")

Output:

Error Table:

[Link]. Error Modification


1. SyntaxWarning: invalid escape sequence '\.' Use r to get raw string.

Explanation:

[Link] regular expression.

[Link] input of a email from the user.

[Link] match check the pattern of an email and input.

Pattern: r'^[a-z0-9]+@gmail\.com$

r – raw string

^ – start of the string

[a-z0-9] – string contains small letters from a to z and numbers froom 0 to 9.

+ – one or more string

@gmail – matches the string

\. – escapes it, so it means a dot (.)

Com – matches the string

$ – end of the string

[Link] the input is valid or not and print the output.

[Link] a program to Check if a given number is a valid Indian mobile number (10 digits, starts with 6-9).

Aim: To Check if a given number is a valid Indian mobile number.

Program:

print("Vaasita - AIE24008")

print()

65
import re

phn=input("Enter a phone number: ")

num=[Link]('[6-9][0-9]{9}',phn)

if num:

print("Valid phone number..")

else:

print("Inavlid phone number..")

Output:

Error Table:

[Link]. Error Modification


1. NameError: name 're' is not defined. Did you Import re.
forget to import 're'?

Explanation:

[Link] regular expression.

[Link] input of a phone number from the user.

[Link] match check the pattern of phone number and input.

Pattern: [6-9][0-9]{9}

[6-9] – string contains numbers 6 to 9

[0-9] – string contains numbers from 0 to 9

{9} – string has 9 number of digits

[Link] if the input is valid or not and print the output.

3. Write a program to extract all dates in the format dd-mm-yyyy.

Aim: To extract all dates in the format dd-mm-yyyy.

Program:

print("Vaasita - AIE24008")

66
print()

import re

date = input("Enter Date (dd-mm-yyyy) : ")

pattern = r"^(0[1-9]|[12][0-9]|[3][01])\-(0[1-9]|1[0-2])\-\d{4}$"

op = [Link](pattern,date)

if op:

print("Valid Date")

else:

print("Invalid Date")

Output:

Error Table:

[Link]. Error Modification


1. NameError: name 're' is not defined. Did you Import re.
forget to import 're'?

Explanation:

[Link] regular expression.

[Link] an input from the user for the date month and year(dd-mm-yyyy).

[Link] the pattern to print the date

Pattern: r"^(0[1-9]|[12][0-9]|[3][01])\-(0[1-9]|1[0-2])\-\d{4}$"

r – raw string

^ - start of a string

0[1-9] - Matches 01 to 09 (days with leading zero).

[12][0-9] - Matches 10 to 29.

[3][01] - Matches 30 or 31.

| - The | operator means OR between these three possibilities.

0[1-9] - Matches months 01 to 09.

1[0-2] - Matches 10, 11, 12.

\d - Matches any digit (0–9).

{4} - Exactly 4 digits

$ - end of a string

67
[Link] match print the date.

4. Write a program to Extract Hashtags from Social Media Post ("Learning #Python is fun! #AI
#MachineLearning”)

Aim: To Extract Hashtags from Social Media Post.

Program:

print("Vaasita - AIE24008")

print()

import re

post="Singing is therapy #Voice#Melodies"

pattern=r"#\w+"

hashtag=[Link](pattern,post)

print("Hashtags: ",hashtag)

Output:

Error Table:

[Link]. Error Modification


1. SyntaxWarning: invalid escape sequence '\.' Use r to get raw string.

Explanation:

[Link] regular expression.

[Link] an input string of a text containing hashtags.

[Link] the pattern to extract the words with hastags.

Pattern : r"#\w+"

r – raw string

# - string matches #

\w – string matches word characters

+ - one or more string

[Link] findall print the matching words having hashtags.

5. write a program to Extract URLs from a given text (Visit our site at [Link] or follow
[Link]

Aim: To Extract URLs from a given text.

68
Program:

print("Vaasita - AIE24008")

print()

import re

text="Google: [Link] is one of the top companies"

pattern = r"https?://[^\s]+"

urls = [Link](pattern, text)

print("URLs Found:", urls)

Output:

Error Table:

[Link]. Error Modification


1. SyntaxWarning: invalid escape sequence '\.' Use r to get raw string.

Explanation:

[Link] regular expression.

[Link] an input string of a text containing URL.

[Link] the pattern to extract the URL from the sentence.

pattern : r"https?://[^\s]+"

r – raw string

https – matches the string

? – s is taken 0 times or 1 time

Matches the literal string ://

[^\s] – whitespace is allowed

+ - one or more character

[Link] findall print the matching URL from the pattern.

6. Write a program to mask the credit card number. Replace all the digits with star(*) except the last
four(4) characters. (Card No - "1234-5678-9876-5432")

Aim: To mask the credit card number.

Program:

print("Vaasita - AIE24008")

69
print()

import re

card="1234-4567-7890-0123"

masked = [Link](r"\d{4}-\d{4}-\d{4}-(\d{4})", r"****-****-****-\1", card)

print('Masked Card: ',masked)

Output:

Error Table:

[Link]. Error Modification


1. Sub is not defined Add [Link]

Explanation:

[Link] regular expression.

[Link] an input string of a card number.

[Link] the pattern to mask the last numbers except last four numbers.

Pattern: r"\d{4}-\d{4}-\d{4}-(\d{4})", r"****-****-****-\1"

r – raw string

\d{4}-\d{4}-\d{4} :

This matches three groups of 4 digits each, separated by hyphens

(\d{4}):

Another group of exactly 4 digits

The ****-****-****- part replaces the first 12 digits with ****.

\1 = "the first captured group" → the last 4 digits matched earlier.

[Link] sub print the the masked card number.

7. Write a program to Extract all words starting with a capital letter from the given text.

Text - "Python is Developed by Guido Van Rossum."

Aim: To Extract all words starting with a capital letter from the given text.

Program:

print("Vaasita - AIE24008")

print()

import re

70
sentence = "Python is a simple coding language."

pattern = r"\b[A-Z][a-zA-Z]*\b"

words = [Link](pattern, sentence)

print("Capitalized Words:", words)

Output:

Error Table:

[Link]. Error Modification


1. AttributeError: module 're' has no attribute Write findall instead of findal.
'findal'.

Explanation:

[Link] regular expression.

[Link] an input string of a text containing capital letters.

[Link] the pattern to extract the words with capital letters.

pattern : r"\b[A-Z][a-zA-Z]*\b"

r – raw string

[A-Z] – contains capital letters A to Z

[a-zA-Z] – contains capital and small letters

[Link] findall print the matching words.

8. Write a regex to extract all PAN card numbers (format: 5 letters + 4 digits + 1 letter).

Text - "Employee PAN: ABCDE1234F, Another PAN: XYZAB6789K"

Example Domain

Aim: To extract all pan card numbers.

Program:

print("Vaasita - AIE24008")

print()

import re

text = "Employee PAN: VAASUU2437B, Another PAN: BONTHU2007R"

pattern = r"\b[A-Z]{6}[0-9]{4}[A-Z]\b"

pans = [Link](pattern, text)

71
print("PAN Numbers:", pans)

Output:

Error Table:

[Link]. Error Modification


1. AttributeError: module 're' has no attribute Write findall instead of findal.
'findal'.

Explanation:

[Link] regular expression.

[Link] an input string containing PAN card numbers.

[Link] the regex pattern to identify PAN card numbers.

pattern : r"\b[A-Z]{6}[0-9]{4}[A-Z]\b"

r – raw string
[A-Z]{6} – contains 6 capital letters A to Z

[0-9]{4} – contains 4 numbers

[A-Z] – contains a capital letter

[Link] findall print the matching strings.

WEEK – 8

[Link] a program that creates a thread to print numbers from 1 to 5 with a delay of 1 second between
each number.

Aim: To print numbers from 1 to 5 with a delay of 1 second between each number using threads.

Program:

print("Vaasita - 24008")

print()

import threading

import time

def numbers():

for i in range(1,6):

print(i)

[Link](1)

print("numbers from 1 to 5")

72
t=[Link](target=numbers)

[Link]()

[Link]()

Output:

Error table:

[Link]. Error Modification


1. Indentation error Space after the def.

Explanation:

This simple program creates one thread to print numbers 1–5. The numbers() function prints each number,
waiting one second before the next. A thread runs this function using Thread(target=numbers). The start()
method begins execution, while join() makes the main program wait until the thread completes its task.

[Link] a program with two threads: one prints numbers (1–5) and the other prints letters (A–F).

Aim: To create two threads : one – one prints 1-5 another prints A-F.

Program:

print("Vaasita - 24008")

print()

import threading

def numbers():

for i in range(1,6):

print(i)

print("numbers from 1 to 5")

def letters():

for ch in ['A', 'B', 'C', 'D', 'E', 'F']:

print(ch)

print("letters from A to F")

n=[Link](target=numbers)

t=[Link](target=letters)

73
[Link]()

[Link]()

[Link]()

[Link]()i

Output:

Error table:

[Link]. Error Modification


1. NameError: name 'A' is not defined A should be defined as ‘A’.
2. TypeError: 'str' object cannot be interpreted as String do not have range.
an integer

Explanation:

Here, two threads run together. One prints numbers 1–5, and the other prints letters A–F. Each pauses for one
second before printing the next. Both threads start using start(), and their results may appear mixed because they
run at the same time. join() ensures completion before program ends.

[Link] a program to create a custom-named thread "SuperThread" and display its name
during execution.

Aim: To create a custom named thread “superThread” and display its name.

Program:

print("Vaasita - 24008")

print()

import threading

def task():

print("This is:", threading.current_thread().name)

t = [Link](target=task, name="SuperThread")

[Link]()

74
[Link]()

Output:

Error table:

[Link]. Error Modification


1. .jin not defined .join is the attribute

Explanation:

This program creates a thread with a custom name. By setting name="SuperThread" while creating the thread,
we can identify it easily. Inside the task() function, the thread prints its own name using
threading.current_thread().name. Naming threads helps in debugging and managing multiple threads by making
them more readable.

[Link] a program that starts a thread and checks if it is alive before and after execution.

Aim: To start a thread and check if it is alive before and after execution

Program:

print("Vaasita - 24008")

print()

import threading

import time

def task():

print("Thread is running...")

[Link](2)

print("Thread finished!")

t = [Link](target=task)

print("Before starting thread: Is alive?", t.is_alive())

[Link]()

print("After starting thread: Is alive?", t.is_alive())

[Link]()

print("After [Link](): Is alive?", t.is_alive())

Output:

75
Error table:

[Link]. Error Modification


1. .jin not defined .join is the attribute

Explanation:

This program uses is_alive() to check thread status. Before starting, it shows False. After calling start(), it prints
True because the thread is running. After the thread finishes and join() completes, is_alive() returns False again.
This demonstrates how to monitor whether a thread is active during execution.

[Link] a program that creates 3 worker threads, each printing its own name.

Aim: To create 3 workers threads each printing its own name.

Program:

print("Vaasita - 24008")

print()

import threading

def worker():

print("Running:", threading.current_thread().name)

for i in range(1, 4):

t = [Link](target=worker, name=f"Worker-{i}")

[Link]()

[Link]()

Output:

76
Error table:

[Link]. Error Modification


1. Did not write the target We should write the target

Explanation:

This program creates three worker threads. Each thread is given a unique name like Worker-1, Worker-2, and
Worker-3. Inside the worker() function, the thread prints its own name using current_thread().name. The loop
starts and joins each thread one after another, showing individual thread execution clearly.

[Link] a program to demonstrate a daemon thread that runs in the background.

Aim: To demonstrate a deamon thread that runs in the background.

Program:

print("Vaasita - 24008")

print()

import threading, time

def background():

for i in range(10):

print("Daemon thread running...")

[Link](1)

d = [Link](target=background, daemon=True)

[Link]()

[Link](3)

print("Main program ending")

Output:

Error table:

[Link]. Error Modification


1. Gave the wrong true or false To run daemon we should write daemon=true

77
Explanation:

This program shows a daemon thread, which runs in the background. The thread prints a message continuously
but is marked as daemon=True. When the main program ends, daemon threads automatically stop. Here, after
three seconds, the main program finishes, and the background thread also ends without explicit termination.

LAB – 9

Develop an GUI applications using python Tkinter

1. Develop a python GUI application to create a student registration form with student details and
display them after successful registration.

AIM: To write a python code to create a student registration form using GUI

Program:

from tkinter import *

window=Tk()

l6=Label(window,text="[Link].U4AIE24008")

[Link](x=0,y=0)

v1=StringVar()

v2=StringVar()

v3=StringVar()

v4=StringVar()

def details():

x1=[Link]()

x2=[Link]()

x3=[Link]()

x4=[Link]()

[Link](text=f"Name: {x1}\nRoll No: {x2}\nEmail: {x3}\nYear: {x4}")

l1=Label(window,text="name")

[Link](x=0,y=30)

e1=Entry(window,width=20,textvariable=v1)

[Link](x=80,y=30)

l2=Label(window,text="rollno")

[Link](x=0,y=60)

e2=Entry(window,width=20,textvariable=v2)

78
[Link](x=80,y=60)

l3=Label(window,text="email")

[Link](x=0,y=90)

e3=Entry(window,width=20,textvariable=v3)

[Link](x=80,y=90)

l4=Label(window,text="year of study")

[Link](x=0,y=120)

e4=Entry(window,width=20,textvariable=v4)

[Link](x=80,y=120)

b1=Button(window,text="submit",command=details)

[Link](x=0,y=150)

l5=Label(window,text="")

[Link](x=0,y=180)

[Link]()

OUTPUT:

Error Table:

S. No Error Message Error Rectification

1. Name Error: name 'l5' is not defined Ensure l5 is defined before it is used
inside details()

2. Type Error: details() takes 0 positional mistakenly write command=details()


arguments but 1 was given instead of command=details.

Explanation:

1. from tkinter import *

79
 Imports all Tkinter classes and functions to create the GUI.

2. window = Tk()

 Creates the main application window where all widgets will be placed.

3. l6 = Label(window, text="[Link].U4AIE24011")

 A label is created to display your ID.

 Placed at coordinates (0,0) with .place().

4. v1, v2, v3, v4 = StringVar()

 These variables are special Tkinter objects used to store and retrieve text from input fields (Entry).

 Each field in the form (Name, Roll No, Email, Year) is connected to one of these variables.

5. def details(): ...

 This function is called when the Submit button is clicked.

 .get() fetches the current text entered into each Entry field.

 [Link](...) updates the output label (l5) to display the formatted details.

6. Input Labels and Entry fields (l1, e1, … l4, e4)

 Labels (Label) describe each input field: Name, Roll No, Email, Year of study.

 Entry widgets (Entry) allow the user to type text.

 Each Entry is linked to its corresponding StringVar (textvariable=v1, etc.).

7. Submit Button (b1)

 Created with Button(window, text="submit", command=details).

 When clicked, it runs the details() function.

8. Output Label (l5)

 Initially blank (text="").

 Updated dynamically inside details() with the user’s input.

9. [Link]()

 Starts the Tkinter event loop.

 Keeps the window open and listens for user actions (typing, clicking, etc.).

[Link] a GUI application to create a calculator, where the user has to click on the numbers and symbol
(Arithmetic operation). Based on the symbol, it has to display the output.

AIM: To write a python code to create a calculator using GUI

Program:

from tkinter import *

window = Tk()

80
[Link]("Calculator")

expression = ""

text_input = StringVar()

entry = Entry(window, textvariable=text_input, bd=8)

[Link](fill="x")

def press(num):

global expression

expression += str(num)

text_input.set(expression)

def equalpress():

try:

global expression

result = str(eval(expression))

text_input.set(result)

expression = result

except:

text_input.set("Error")

expression = ""

def clear():

global expression

expression = ""

text_input.set("")

frame1 = Frame(window)

[Link]()

Button(frame1, text="1", width=8, height=2, command=lambda: press(1)).pack(side=LEFT)

Button(frame1, text="2", width=8, height=2, command=lambda: press(2)).pack(side=LEFT)

Button(frame1, text="3", width=8, height=2, command=lambda: press(3)).pack(side=LEFT)

frame2 = Frame(window)

[Link]()

Button(frame2, text="4", width=8, height=2, command=lambda: press(4)).pack(side=LEFT)

Button(frame2, text="5", width=8, height=2, command=lambda: press(5)).pack(side=LEFT)

Button(frame2, text="6", width=8, height=2, command=lambda: press(6)).pack(side=LEFT)

frame3 = Frame(window)

81
[Link]()

Button(frame3, text="7", width=8, height=2, command=lambda: press(7)).pack(side=LEFT)

Button(frame3, text="8", width=8, height=2, command=lambda: press(8)).pack(side=LEFT)

Button(frame3, text="9", width=8, height=2, command=lambda: press(9)).pack(side=LEFT)

frame4 = Frame(window)

[Link]()

Button(frame4, text="0", width=8, height=2, command=lambda: press(0)).pack(side=LEFT)

Button(frame4, text="*", width=8, height=2, command=lambda: press("*")).pack(side=LEFT)

Button(frame4, text="-", width=8, height=2, command=lambda: press("-")).pack(side=LEFT)

frame5 = Frame(window)

[Link]()

Button(frame5, text="+", width=8, height=2, command=lambda: press("+")).pack(side=LEFT)

Button(frame5, text="/", width=8, height=2, command=lambda: press("/")).pack(side=LEFT)

Button(frame5, text="=", width=8, height=2, command=equalpress).pack(side=LEFT)

frame6 = Frame(window)

[Link]()

Button(frame6, text="Clear", width=26, height=2, bg="lightcoral", command=clear).pack(side=LEFT)

[Link]()

OUTPUT:

Error Table:

S. No Error Message Error Rectification

82
1. Name Error: name 'text_input' is not defined Make sure text_input = StringVar() is
defined before using it in Entry or
functions.

2. Type Error: press() missing 1 required Use lambda x=b: press(x) when creating
positional argument buttons, do not call press() directly.

Explanation:

1. from tkinter import *

 Imports all Tkinter classes and functions for GUI creation.

2. Main window setup

 window = Tk(): creates the main application window.

 [Link]("Calculator"): sets the window title to "Calculator".

3. Entry field

 expression = "": stores the current calculator input as a string.

 text_input = StringVar(): Tkinter variable to link the Entry widget to expression.

 Entry(window, textvariable=text_input, bd=8).pack(fill="x"):

o Creates an input field where the user sees numbers and operations.

o bd=8 gives border thickness.

o fill="x" makes the Entry stretch horizontally.

4. Functions

1. press(num)

o Adds the pressed button value to expression.

o Updates the Entry field using text_input.set(expression).

2. equalpress()

o Evaluates the expression using eval().

o Displays the result in the Entry field.

o Handles errors (like division by zero) and shows "Error".

o Resets expression after error.

3. clear()

o Resets expression and clears the Entry field.

5. Button layout

 buttons list defines the calculator layout row by row.

 Loops through buttons to create Frame for each row.

83
 Inside each row, creates a Button for each item:

o If button is "=", calls equalpress().

o Otherwise, uses lambda x=b: press(x) to pass the button value to press().

 pack(side=LEFT) aligns buttons horizontally in the frame.

6. Clear button

 Creates a separate row for the Clear button.

 Width=26 to span all columns, height=2 for button size.

 bg="lightcoral" gives a red background.

 Calls clear() when clicked.

7. [Link]()

 Starts Tkinter’s event loop.

 Keeps the window open and responds to button clicks.

LAB-10

Task-1 :- Write a Python program using BeautifulSoup to:

1. Fetch the HTML content of a web page ([Link]

2. Extract and print the following details:

a. The title text of the page

b. The first paragraph (<p>) on the page

c. The first 5 hyperlinks (<a> tags) and their URLs

d. The total number of <a> tags on the page

e. Print the first 300 characters of all visible text on the page.

f. The page title text

g. All the main headings on the page (<h1>, <h2>, and <h3> tags)

h. The number of <div> tags present on the page

i. All elements with the class name "menu" (print only their text content)

Aim: To fetch the content of Amrita page using Beautiful soup

Program:

import requests

from bs4 import BeautifulSoup

url = '[Link]

response = [Link](url)

84
[Link] = 'utf-8'

soup = BeautifulSoup([Link], '[Link]')

title_tag = [Link]

title_text = title_tag.string if title_tag else "No title found"

print("Page Title:", title_text)

print("*******************************************")

first_paragraph = [Link]('p')

print("First Paragraph:", first_paragraph.get_text() if first_paragraph else "No paragraph found")

print("*******************************************")

all_links = soup.find_all('a')

print("First 5 hyperlinks and URLs:")

for link in all_links[:5]:

href = [Link]('href')

text = link.get_text().strip()

print(f"Text: {text}, URL: {href}")

print("*******************************************")

print("Total number of <a> tags:", len(all_links))

print("*******************************************")

page_text = soup.get_text(separator=' ', strip=True)

print("Page Text Sample (first 300 chars):")

print(page_text[:300])

print("*******************************************")

headings = soup.find_all(['h1', 'h2', 'h3'])

print("Main Headings:")

for h in headings:

print(h.get_text().strip())

print("*******************************************")

div_count = len(soup.find_all('div'))

print("Number of <div> tags:", div_count)

print("*******************************************")

menu_elements = soup.find_all(class_='menu')

print("Elements with class 'menu':")

for elem in menu_elements:

85
print(elem.get_text().strip())

Output:

86
Error table:

Error Error rectification

87
[Link] Happens if the website is down, or there’s no internet
connection. Fix: Check your internet or try another URL.

[Link] The server is taking too long to respond. Fix: Use


[Link](url, timeout=10) to limit wait time.

AttributeError: 'NoneType' object has no Occurs when the page has no <title> tag. Fix: Use title_tag
attribute 'string' = [Link] and check if it exists before accessing .string.

AttributeError: 'NoneType' object has no Happens when there is no <p> tag on the page. Fix: Check
attribute 'get_text' if the result is not None before calling .get_text().

Explanation:
Import Libraries

● requests → for sending HTTP requests to fetch webpage content.

● BeautifulSoup → for parsing HTML and extracting information.

Fetch the Web Page

● Sends a GET request to the URL.

● Sets encoding to UTF-8 to handle special characters.

Parse HTML

● Creates a BeautifulSoup object to navigate the HTML structure.

Extract Page Title

● Gets the text inside the <title> tag.

● Checks if the <title> tag exists to avoid errors.

Extract First Paragraph

● Finds the first <p> tag on the page.

● Prints its text content if it exists.

Extract Hyperlinks

● Finds all <a> tags.

● Prints the first 5 links and their URLs.

● Counts and prints the total number of <a> tags.

Extract Page Text

● Extracts all visible text using .get_text().

● Prints the first 300 characters.

Extract Headings

88
● Finds all <h1>, <h2>, and <h3> tags.

● Prints their text content.

Count <div> Tags

● Counts all <div> tags on the page.

Extract Elements with Class "menu"

● Finds all elements with class "menu".

● Prints only their text content.

Error Handling

● Checks for None values to avoid AttributeError.

● Ensures proper decoding with UTF-8 to prevent UnicodeDecodeError.

Task-2 :- Write a Python program using the requests library to:

1. Send a GET request to the URL ([Link]

2. Print the following details about the response:

a. The status code (e.g., 200 means success, 404 means not found)

b. The final URL after redirections (if any)

c. The server type from the response headers


d. The content type
e. The encoding used to decode text
f. The time taken to get the response (in seconds)
g. Whether the request was successful or not (True if status code < 400)

Aim: To get the details of Amrita website using requests library.

Program:

import requests
url = '[Link]
response = [Link](url)
print("Status Code:", response.status_code)
print("Final URL:", [Link])
print("Server Type:", [Link]('Server'))
print("Content-Type:", [Link]('Content-Type'))
print("Encoding:", [Link])
print("Elapsed Time:", [Link].total_seconds())
print("Request Successful?:", [Link])

Output:

89
Error table:

Error Error rectification

[Link] Check your internet or try another URL.

[Link] Use [Link](url, timeout=10) to set a timeout.

Explanation:

Import requests

● Allows sending HTTP requests to web servers in Python.

Define the URL

url = '[Link]

● The target webpage to fetch.

Send a GET request

response = [Link](url)

● Fetches the content of the webpage.

Print Status Code

response.status_code

● Shows whether the request was successful (e.g., 200 = OK).

Print Final URL

[Link]

● Displays the URL after any redirects.

Print Server Type

[Link]('Server')

● Indicates the type of server hosting the page (e.g., Apache, nginx).

Print Content Type

[Link]('Content-Type')

● Shows the type of content returned (e.g., text/html, application/json).

90
Print Encoding

[Link]

● Displays how the response text is decoded.

Print Elapsed Time

[Link].total_seconds()

● Time taken (in seconds) for the server to respond.

Print if Request was Successful

[Link]

● Returns True if status code < 400, otherwise False.

LAB-11

Write Python programs to demonstrate the following NumPy operations:

11. Creation of arrays

12. array attributes

13. Performing arithmetic operations on NumPy arrays.

14. Performing statistical operations

15. Using aggregate functions

16. Applying trigonometric and mathematical functions.

17. Performing indexing and slicing on arrays.

18. Using logical operations and Boolean indexing.

19. Demonstrating reshaping and flattening of arrays.

20. Demonstrating stacking and splitting of arrays.

21. Performing advanced operations

Programs:

1. Creation of arrays

import numpy as np

arr1=[Link]([10,20,30])

arr2=[Link]([[1,2,3],[4,8,6]])

print("1d array:\n",arr1)

print("2d array:\n",arr2)

output:

91
2. array attributes

print("1d array dimension:\n",[Link])

print("2d array dimension:\n",[Link])

print("arr2 is an ", [Link],"dimensional array")

print("size:",[Link])

print("item size:", [Link])

print("datatype:",[Link])

output:

3. Performing arithmetic operations on NumPy arrays.

arr3=[Link]([[1,5,3],[4,5.6,6]])

print("addition:",arr2+arr3)

print("subtraction:",arr2-arr3)

print("multiplication:",arr2*arr3)

print("divison:",arr2/arr3)

print("power:",arr1**2)

output:

92
4. Performing statistical operations

print("sum:",[Link](arr1))

print("mean:",[Link](arr1))

print("median:",[Link](arr1))

print("standard deviation:",[Link](arr1))

print("maximum:",[Link](arr1))

print("minimum:",[Link](arr1))

output:

5. Using aggregate functions

print("sum of all elements:",[Link](arr2))

print("sum of columns:",[Link](arr2,axis=0))

print("sum of rows:",[Link](arr2,axis=1))

print("max of columns:",[Link](arr2,axis=0))

print("max of rows:",[Link](arr2,axis=1))

output:

93
6. Applying trigonometric and mathematical functions.

angles=[Link]([0,30,45,60])

rad = np.deg2rad(angles)

print("sin:",[Link](rad))

print("cos:",[Link](rad))

print("tan:",[Link](rad))

print("square root :",[Link](arr1))

output:

7. Performing indexing and slicing on arrays.

print("first element:",arr1[0])

print("last element:",arr1[-1])

print("slice [1:4]:",arr1[1:4])

print("first row:",arr2[0,:])

print("second column:",arr2[:,1])

print("sub matrix:",arr2[1:,1:])

output:

8. Using logical operations and Boolean indexing.

x=[Link]([1,2,3])

y=[Link]([2,2,3])

94
print("equal:",x==y)

print("greater:",x>y)

print("less:",x<y)

print("logical AND:",np.logical_and(x>1,y<5))

output:

9. Demonstrating reshaping and flattening of arrays.

arr=[Link](12)

print("original array:",arr)

mat= [Link](3,4)

print("reshaped 3x4:\n",mat)

flat=[Link]() # back to before dimension and array

print("flattend array:",flat)

output:

10. Demonstrating stacking and splitting of arrays.

v_stack=[Link]((arr2,arr3))

print("vertical stack :\n",v_stack)

h_stack=[Link]((arr2,arr3))

print("horizontal stack :",h_stack)

split_arr=[Link]([Link](10),2)

print("split arrays:",split_arr)

output:

95
11. Performing advanced operations

print("elemnet wise:",arr2*arr3)

arr4=[Link]([[1,2],[4,5]])

arr5=[Link]([[4,5],[6,7]])

print("matrix multiplication:",[Link](arr4,arr5))

print("original matrix:\n",arr2)

print("transpose matrix:\n",arr2.T)

Output:

Error Table:

S. No Error Message Error Rectification

1. ModuleNotFoundError: No module named Make sure u import numpy before


'numpy' executing codes

2. ValueError: operands could not be broadcast Use arrays with matching or compatible
together with shapes (2,3) (3,2) shapes for arithmetic operations.

3. IndexError: index out of bounds for axis Access elements within valid index ranges
only.

96
Explanation:

Creation of Arrays:

● The code begins by importing NumPy (import numpy as np).

● Arrays are created using [Link]().

● arr1 is a 1D array with elements [10, 20, 30].

● arr2 is a 2D array with two rows and three columns.

● Both arrays are printed to show their structure.

Array Attributes:

● The program displays properties of arrays using built-in attributes:

○ .shape → returns the number of rows and columns.

○ .ndim → shows the number of dimensions.

○ .size → total number of elements.

○ .itemsize → memory used by each element (in bytes).

○ .dtype → data type of array elements.

● This helps to understand array configuration and storage details.

Arithmetic Operations:

● A new array arr3 is created with decimal and integer values.

● Element-wise addition, subtraction, multiplication, and division are performed between arr2 and arr3.

● arr1**2 computes the square of each element (power operation).

● These operations are vectorized — done without explicit loops.

Statistical Operations:

● Statistical functions like [Link](), [Link](), [Link](), [Link](), [Link](), and [Link]() are applied
on arr1.

● They return measures of central tendency and spread of the array elements.

Aggregate Functions:

● Aggregations like sum and max are calculated:

○ Over all elements.

○ Column-wise (axis=0).

○ Row-wise (axis=1).

97
● This demonstrates NumPy’s ability to perform grouped data calculations.

Trigonometric and Mathematical Functions:

● An array of angles is converted from degrees to radians using np.deg2rad().

● Trigonometric functions ([Link](), [Link](), [Link]()) are applied on the radian values.

● [Link]() finds the square root of each element in arr1.

Indexing and Slicing:

● Demonstrates accessing array elements using indices.

● For 1D array: first, last, and a slice [1:4] are printed.

● For 2D array: specific rows, columns, and sub-matrices are accessed using slicing (arr2[row, column]).

Logical Operations and Boolean Indexing:

● Two arrays x and y are compared using relational operators (==, >, <).

● np.logical_and() checks conditions across both arrays.

● Outputs Boolean arrays indicating True/False for each element comparison.

Reshaping and Flattening:

● An array arr is created using [Link](12) (values from 0–11).

● .reshape(3,4) converts the 1D array into a 3×4 matrix.

● .flatten() brings it back to 1D form.

● Shows how NumPy allows easy dimensional transformation.

Stacking and Splitting:

● Arrays are combined vertically using [Link]() and horizontally using [Link]().

● [Link]() divides a 1D array into equal parts.

● These functions demonstrate flexible merging and partitioning of arrays.

Advanced Operations:

● Element-wise multiplication of arr2 and arr3 is shown.

● [Link]() performs matrix multiplication between two 2×2 arrays.

● .T is used to get the transpose of a matrix (rows ↔ columns).

● Demonstrates linear algebra and higher-level operations.

LAB – 12

1. Write Python programs to demonstrate the following Pandas operations:

1. Reading data from a file.


2. Viewing and exploring data using functions such as head(), tail(), info(), and describe().
3. Selecting and filtering data using labels (loc[]), integer positions (iloc[]), and conditional filtering.
4. Adding, updating, and deleting columns in a DataFrame.
5. Handling missing data using isnull(), fillna(), and dropna().

98
6. Sorting data using sort_values() .
7. Merging, joining, and concatenating DataFrames.
8. Performing basic statistical operations using built-in Pandas functions
2. Write Python programs to demonstrate the Data Visualization:

1. Univariate analysis using a histogram ([Link]()) in Matplotlib.


2. Univariate analysis using a histplot ([Link]()) in Seaborn.
3. Visualization of categorical variable distribution using a countplot ([Link]()).
4. Bivariate analysis using a scatter plot ([Link]() or [Link]()).
5. Comparison of numerical variable distribution across categories using a boxplot ([Link]()).
6. Multivariate analysis using a pairplot ([Link]()).
7. Visualization of correlations between numerical variables using a heatmap ([Link]()).
8. Representation of aggregated or summarized data using a barplot ([Link]()).
9. Saving a plot or visualization using [Link]().

Programs:

Aim: To read a data from a file

Code:

df=pd.read_csv(r'C:\Users\vaasi\Downloads\archive\[Link]')

df

Output:

99
2.

Aim: To view and explore data from the file

Code:

print([Link]())

100
print([Link]())

print([Link]())

101
print([Link]())

102
3.

Aim: To select and filter data.

Code:

print([Link])

print([Link])

df1["Fuel_Type"]#select single column

103
print("*****multiple columns*****\n", df[['Id', 'Model','Price','Weight','cc']])

Row selection using index

[Link][1]

104
[Link][1]

105
[Link][1:3]#slicing row 1 to 2

#rows selection using index

print([Link][0])#row by position

print([Link][1,3])#second row, 4th column

print([Link][1:3])#slicing from row 1 to 2

print([Link][0])#row by label

106
print([Link][:,1])#all rows, second column

print([Link][0:2,:])#slice first two rows

107
[Link][0,'Fuel_Type'] # accesing a particular cell in this row-0 and column is fuel type

108
Filtering Data

print("************** Single Condition ******************")

print(df[df['Price'] > 20000])

print("************** Multiple Conditions ****************")

print(df[(df['Price'] > 22000) & (df['Fuel_Type'] == 'Petrol')])

109
4.

Aim: To add , update , and delete columns in dataframe

Code:

df['Hike_amount'] = df['Price'] * 0.10

df['Total_price'] = df['Price'] + df['Hike_amount']

df['Hike_amount']

110
df['Total_price']

Inplace

inplace = true Modify the original dataframe

inplace = false Returns new dataframe and old dataframe is unchanges

[Link]

[Link]('Total_price',axis=1,inplace=True)

[Link](1,axis=0,inplace=True)

[Link]

111
5.

Aim: To handle missing data

print([Link]().sum()) # checks missing values

112
113
print([Link](0,inplace=True)) # Replace NaN with 0

[Link](inplace=True) # Drop rows with missing values

# fill missing numeric values with median

[Link]([Link](numeric_only=True),inplace= True) # This is aplicable to only numerical columns

print([Link]().sum()) # verifying the data frame after replacing the NaN with 0

114
115
[Link]

grouped= [Link]('Fuel_Type')['Price'].mean() # group by fuel type and find average price

print(grouped)

6.

Aim: To sort the data from the file

Code:

df.sort_values(by='Price',ascending=False,inplace=True)

df

116
7.

Aim: To merge , join and concatenate dataframes

df3 = [Link]({'ID': [1, 2, 3], 'Name': ['Raj', 'Ram', 'AAshish']})

df4 = [Link]({'ID': [1, 2, 3], 'Salary': [50000, 60000, 70000]})

merged = [Link](df3, df4, on='ID')

print(merged)

# Concatenation of Data Frames w.r.t columns and rows.

df1 = [Link]({'A': [1, 2], 'B': [3, 4]})

df2 = [Link]({'A': [5, 6], 'B': [7, 8]})

#result = [Link]([df1, df2], axis=0) # Combine the two DataFrames vertically (row-wise).

result = [Link]([df1, df2], axis=1) # Combine the two DataFrames horizontally (column-wise).

print(result)

8.

Aim: To perform basic statistical operations

print(df['Price'].mean()) # Average salary

print(df['Price'].max()) # Max salary

print(df['Price'].min()) # Min salary

print(df['Price'].std()) # Standard deviation

117
Data Visualization

Programs:

[Link] analysis ->histogram in matplotlib

import pandas as pd

import [Link] as plt

import seaborn as sns

[Link](df['Price'], bins=20, color='pink', edgecolor='green')

[Link]('Distribution of Car Prices')

[Link]('Price')

[Link]('Frequency')

[Link]()

Output:

118
2. Univariate analysis -> histplot in seaborn

import pandas as pd

import seaborn as sns

import [Link] as plt

[Link](df['Price'], kde=True, color='purple')

[Link]('Price Distribution with KDE')

[Link]()

Output:

[Link] of categorised variable using countplot

import pandas as pd

import seaborn as sns

import [Link] as plt

[Link](x='Fuel_Type', data=df, palette='viridis')

[Link]('Count of Cars by Fuel Type')

[Link]()

Output:

119
[Link] analysis using scatter plot

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

[Link](df['Age_08_04'], df['Price'], color='teal')

[Link]('Car Price vs Age')

[Link]('Car Age (in months)')

[Link]('Price')

[Link]()

Output:

120
[Link](x='Age_08_04', y='Price', data=df, hue='Fuel_Type', style='Automatic', palette='Set2')

[Link]('Price vs Age by Fuel Type and Transmission')

[Link]()

Output:

Comparison of numerical variable distribution across categories using a boxplot ([Link]()).

# Box Plot — Price by Fuel Type - Box plots show median, quartiles, and outliers of prices across different
fuel types.

121
[Link](x='Fuel_Type', y='Price', data=df, palette='coolwarm')

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

[Link]()

output:

[Link] analysis

[Link](df[['Price', 'Age_08_04', 'KM', 'HP', 'Fuel_Type']], hue='Fuel_Type', diag_kind='kde')

[Link]()

Output:

122
Visualization of correlations between numerical variables using a heatmap ([Link]()).

[Link](figsize=(10,7))

corr = [Link](numeric_only=True)

[Link](corr, annot=True, cmap='YlGnBu')

[Link]('Correlation Matrix of Numeric Features')

[Link]()

output:

123
Representation of aggregated or summarized data using a barplot ([Link]()).

avg_price = [Link]('Fuel_Type')['Price'].mean().reset_index()

[Link](x='Fuel_Type', y='Price', data=avg_price, palette='mako')

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

[Link]()

output:

124
[Link](x='Automatic', y='Price', data=df, palette='flare')

[Link]('Average Price by Transmission Type')

[Link]()

output:

125
Saving a plot or visualization using [Link]().

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

[Link](x='Fuel_Type', y='Price', data=df)

[Link]('Price vs Fuel Type')

[Link]('C:\Users\chikk\python_codes\image,png', dpi=300)

[Link]()

Error Table:

S. No Error Message Error Rectification

1. FileNotFoundError: [Errno 2] No such Verify file path and ensure correct


file or directory location.

2. KeyError: 'ColumnName' The specified column name is missing


or spelled incorrectly. Check using
[Link]

3. IndexError: single positional indexer is Accessing invalid row/column index.


out-of-bounds Check index range using [Link]
before slicing.

4. ValueError: Length of values does not The number of elements assigned


match length of index doesn’t match the number of rows.
Ensure equal lengths.

5. AttributeError: 'DataFrame' object has Incorrect method or typo used. Verify

126
no attribute '...' method name

6. TypeError: unsupported operand type(s) Performing arithmetic on non-numeric


data. Convert data types using astype()
or to_numeric()

Explanation:

Pandas:

 Series -> 1D labelled array


 Dtaframe -> 2D labelled array
 Display basic info - Shows data types, number of non-null values, and memory usage. #print([Link]())
 Head() -> display first rows , tail() -> display last rows
 Info() -> get summary of column name , types , nulls
 Describe() -> Gives statistics like mean, min, max, etc., for numerical columns
 Iloc[] -> access rows and columns by integer position like last indexing
 Loc[] -> access rows and columns by label (index)
 Conditional selection allows filtering data using logical conditions
 inplace=True permanently changes the original DataFrame
 isnull() identifies missing entries
 fillna() replaces missing values with constants, mean, or median
 dropna() removes incomplete rows or columns
 groupby() groups data based on categories and computes summary statistics (like mean, sum, count)
 sort_values() arranges records in ascending or descending order based on column values
 Pandas provides built-in methods like .mean(), .max(), .min(), .std() for numeric analysis

Data Visualization:

 Import pandas as pd -> for data manipulation


 Import [Link] as plt -> for basic plotting
 Import seaborn as sns -> for advanced , attractive statistical plotting
 Univariate analysis : histogram is used to check the whether prices , the most common price range etc.
 [Link]() -> creates a histogram using seaborn
 Kde -> adds smooth kde curve over the histogram
 [Link]() -> creates a bar plot that counts the number of occurences
 [Link]() -> creates a scatter plot
 The scatter plot helps to visualize how car price changes with age
 Hue -> ‘Fuel_Type’ colours the point based on fuel type
 [Link]() -> creates a box plot which shows the distribution of numeric variable
 [Link]() - > creates a matrix of scatter plot for each pair of numeric values
 [Link]() saves plots as image files (PNG, JPG, etc.) with specified resolution (dpi)

127

You might also like