Python Lab Report: Programming Basics
Python Lab Report: Programming Basics
(22AIE205)
LAB REPORT
Signature
Marks
Date
1
Index:
Week Date Programs List Pg No. Marks
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)
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
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.
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("Section :",section)
print("Year :",year)
Output:
Error Table:
S no Error Modification
Explanation:
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('Section: ',section)
Output:
Error Table:
Explanation:
1. The function input() is used for taking inputs from the user.
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:
10
if age>=18:
else:
Output:
Error Table :
Explanation:
statements.
2. Write a python code to grade a student based on marks. Input marks and display grade:
90–100 O
85-90 A+
80-85 A
75-80 B+
70–75 B
60–69 C
< 60 Fail
Program:
11
per=int(input("Enter the percentage:"))
else:
Output:
Error Table:
Explanation:
12
[Link] a python code 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:
if b>c:
if b>a:
if c>a:
if c>b:
Output:
Error Table:
Explanation:
3. Logical operators and and comparison operators > are used to compare values.
13
[Link] a python code to print all even numbers up to N.
Program:
n=int(input("enter a number:"))
for i in range(n):
if i%2==0:
print(i,end=" ")
Output:
Error Table:
Explanation:
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).
Program:
password='12345'
for i in range(3):
if attempt==password:
print("welcome..")
else:
Output:
14
Error Table:
Explanation:
Program:
n=int(input("Enter a number:"))
factorial=1
for i in range(1,n+1):
factorial*=i
print(factorial)
15
Output:
Error Table:
Explanation:
4. fact = fact * i multiplies the result with each i to compute the factorial.
Program:
print('Vaasita - AIE24008')
a=0
b=1
count=0
print("Fibonacci series:")
print(a,end=" ")
a=b
b=a+b
count+=1
Output:
16
Error Table:
Explanation:
1. Fibonacci Series starts with 0 1, and each number is the sum of the previous two.
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.
Program:
print('Vaasita - AIE24008')
n=int(input("Enter a number:"))
length=len(str(n))
if n==result:
else:
Output:
17
Error Table:
1. IndentationError: expected an indented Make sure all lines under while and if
block are properly indented
Explanation:
[Link] Number (3-digit): A number is Armstrong if the sum of the cubes of its digits equals the number
itself.
WEEK – 3
[Link] a python program to check whether the given number is Prime Number or not.
Program:
print('Vaasita - AIE24008')
n=int(input("Enter a number:"))
if n<=1:
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:
Output:
Error Table:
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:
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.
[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:
19
• ₹75 for 201–300 units
Aim: To calculate the electricity bill based on the number of units consumed
Program:
print('Vaasita - AIE24008')
rate=1.5*units
surcharge=25
rate=2.5*units
surcharge=50
rate=4.0*units
surcharge=75
rate=6.0*units
surcharge=100
else:
rate=7.5*units
surcharge=150
bill=rate+surcharge
Output:
Error Table:
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:
2. fixed rate per unit and surcharge is applied based on the range the units fall into.
Program:
print('Vaasita - AIE24008')
total_amt=amt-withdraw
Output:
Error Table:
Explanation:
21
Aim: To create a Menu-Driven Calculator
Program:
print('Vaasita - AIE24008')
a=int(input("Enter a number:"))
b=int(input("Enter a number:"))
if op=='+':
s=a+b
elif op=='-':
s=a-b
elif op=='*':
s=a*b
elif op=='/':
s=a/b
Output:
Error Table:
Explanation:
1. The program takes two numbers and an operator as input from the user.
Note: Keeps prompting until correct credentials are entered or attempts are exhausted.
Program:
print('Vaasita - AIE24008')
22
username="vaasita"
password="12345"
attempt=3
for i in range(attempt):
name=input("Enter username:")
print("Login Successfull....")
print("Welcome...")
break
i+=1
i+=1
if i==attempt:
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:
Program:
print('Vaasita - AIE24008')
password=input("Enter a paasword:")
if len(password) < 8:
elif([Link]()):
if([Link]()):
elif([Link]()):
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] the length is greater than 8 and have letters along with numbers it gives strongest password.
Program:
print('Vaasita - AIE24008')
while True:
print("1. Home")
print("2. Profile")
print("3. Settings")
print("4. About")
print("5. Help")
print("6. Exit")
if choice == "1":
25
print(" Exiting... Thank you!")
break
else:
Output:
Error Table:
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:
3. for profile 2 , for settings 3 , for about 4 , for help 5 and for exit press 6.
8. Write a python program to generate the below patterns, also include the tracing tables.
12
123
1234
12345
Program:
for i in range(1,6):
for j in range(1,i+1):
print(j,end=" ")
print("")
Output:
Tracing Table:
27
Error Table:
Explanation:
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:
Error Table:
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:
Error Table:
Explanation:
29
Week-4
1. Create a program that manages a grocery shopping list. The program should:
Error Table:
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:
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:
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.
while True:
print("\n------- To-Do List --------")
print("1. Add Task")
print("2. Complete Task (Remove)")
print("3. Display Tasks")
print("4. Exit")
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.")
else:
print("Invalid choice. Please enter a number from 1 to 4.")
Output:
33
Error Table:
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:
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:
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:
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.
36
if letter not in vowels_word:
vowels_word.append(letter)
print("the vowels in the word:",vowels_word)
Output:
Error Table:
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:
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:
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
print("Result:")
for i in x:
for j in y:
38
print(i + j)
Output:
Error Table:
Testcase:
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:
Testcase:
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..
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:
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.
Program:
print("Vaasita - AIE24008")
days=['sunday','monday','tuesday','wednesday','thursday','friday','saturday']
temperature=[43,34,35,38,40,37,41]
print("Weekly temperatures:",weekly_temp)
Output:
Error table:
Explanation:
41
[Link] for and zip make a dictionary for each day each temperature.
[Link] a python program to find all Unique Words from Multiple Paragraphs.
Program:
print("Vaasita - AIE24008")
p1 = "".join(sentence1)
p2 = "".join(sentence2)
l1=[Link]()
l2=[Link]()
unique_words=set(l1+l2)
print(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:
3. Write a python program using Set Operations for the course Survey Analysis.
Task: Perform union, intersection, and symmetric difference.
Program:
print("Vaasita - AIE24008")
set1={'abc','def','ghi','vw','xyz'}
set2={'mno','abc','vw','xyz'}
union_set = [Link](set2)
intersection_set = [Link](set2)
difference_set = [Link](set2)
Output:
Error table:
43
Explanation:
Program:
print("Vaasita - AIE24008")
original = [2,2,3,4,5,5,3,6,1,8,2,3,6,0,9,8,9]
unique = []
[Link](item)
Output:
Error table:
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.
44
Program:
print("Vaasita - AIE24008")
print("Enter a sentence:")
sentence=input()
vowels=['a','e','i','o','u','A','E','I','O','U']
vowels_sentence=[]
if letter in vowels:
vowels_sentence.append(letter)
print(vowels_sentence)
Output:
Error table:
[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={}
if char in count:
45
count[char]+=1
else:
count[char]=1
print("Charecter Count:")
print(f"{char}:{num}")
Output:
Error table:
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.
Program:
print("Vaasita - AIE24008")
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'
student_grade=grade(score)
Output:
Error table:
Explanation:
Program:
print("Vaasita - AIE24008")
inventory = {
'Data Structures': 5,
47
}
while True:
print("5. Exit")
if choice == '1':
print("\nInventory:")
inventory[book] = qty
print("Book added.")
if book in inventory:
del inventory[book]
print("Book removed.")
else:
if book in inventory:
inventory[book] = qty
print("Quantity updated.")
else:
48
print("Goodbye!")
break
else:
print("Invalid choice.")
Output:
49
Error table:
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 .
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'}
print("Concatenated Dictionary:",concatenated)
Output:
Error table:
Explanation:
[Link] program starts with three separate dictionaries: dict1, dict2, and dict3 .
[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.
Program:
print("Vaasita - AIE24008")
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:
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
AIM: Create a base class LibraryItem with attributes title and item_id, and a method display_info().
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.
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]}")
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()
magazine1=magazine("National Geographic",44,102234)
52
book1.display_info()
print()
magazine1.display_info()
Output:
Error table:
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.
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):
class studentrecord:
def __init__(self,roll):
[Link]=roll
def display_roll(self):
class student(person,studentrecord):
person.__init__(self, name)
studentrecord.__init__(self, roll)
s1=student("vaasita",24008)
[Link]()
s1.display_roll()
Output:
Error table:
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.
AIM:
Create a subclass ElectricCar that inherits from Car and has an attribute battery_capacity.
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):
class electriccar(car):
def __init__(self,brand,fuel,battery):
super().__init__(brand,fuel)
[Link]=battery
def display(self):
55
car1=electriccar("BMW","petrol","81.6KW/h")
car1.display_brand()
car1.display_fuel()
[Link]()
Output:
Error table:
Explanation:
[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.
AIM:
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):
class dog(animal):
56
def speak(Self):
print("Dog barks")
class cat(animal):
def speak(self):
print("Cat meows")
animals=[animal(),dog(),cat()]
[Link]()
Output:
Error table:
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.
AIM:
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):
acc1=bankaccount(5000)
acc2=bankaccount(10000)
balance=acc1+acc2
Output:
Error table:
Explanation:
2. Overloads the + operator so you can add two bankaccount objects directly.
[Link] 2 accounts with balance . add them and print the balance.
58
AIM:
Using the abc module, create an abstract class Payment with an abstract method
make_payment(amount).
Create subclasses:
• CreditCardPayment
• UpiPayment
Program:
print("Vaasita - AIE24008")
print()
class Payment(ABC):
@abstractmethod
pass
class CreditCardPayment(Payment):
class UpiPayment(Payment):
if __name__ == "__main__":
payment_method = UpiPayment()
payment_method.make_payment(1500)
Output:
Error table:
59
Explanation:
[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.
AIM:
Add methods:
• deposit(amount)
• withdraw(amount)
• get_balance()
Task: Write a program to create an account, deposit money, withdraw money, and display the balance.
Program:
print("Vaasita - AIE24008")
print()
class BankAccount:
self.__balance = balance
if amount > 0:
self.__balance += amount
print(f"Deposited: ₹{amount}")
else:
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)
Output:
Error table:
Explanation:
[Link] get balance to implement the print statement to print the remaining balance in the account.
AIM:
Create subclasses:
61
• Developer (overrides work() to print "Developer writes code")
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):
class developer(employee):
def work(self):
class manager(employee):
def work(self):
employees=[employee(),developer(),manager()]
[Link]()
Output:
Error table:
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 .
AIM:
Using the abc module, create an abstract class Ride with an abstract method calculate_fare(distance).
Create subclasses:
Create a Booking class that takes a Ride object and a distance, and has a method confirm_booking() to
display the fare.
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()
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:
Explanation:
[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.
Program:
print("Vaasita - AIE24008")
print()
import re
email=[Link](r'^[a-z0-9]+@gmail\.com$', string)
if email:
print("Valid Email..")
64
else:
print("Invalid Email..")
Output:
Error Table:
Explanation:
Pattern: r'^[a-z0-9]+@gmail\.com$
r – raw string
[Link] a program to Check if a given number is a valid Indian mobile number (10 digits, starts with 6-9).
Program:
print("Vaasita - AIE24008")
print()
65
import re
num=[Link]('[6-9][0-9]{9}',phn)
if num:
else:
Output:
Error Table:
Explanation:
Pattern: [6-9][0-9]{9}
Program:
print("Vaasita - AIE24008")
66
print()
import re
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:
Explanation:
[Link] an input from the user for the date month and year(dd-mm-yyyy).
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
$ - 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”)
Program:
print("Vaasita - AIE24008")
print()
import re
pattern=r"#\w+"
hashtag=[Link](pattern,post)
print("Hashtags: ",hashtag)
Output:
Error Table:
Explanation:
Pattern : r"#\w+"
r – raw string
# - string matches #
5. write a program to Extract URLs from a given text (Visit our site at [Link] or follow
[Link]
68
Program:
print("Vaasita - AIE24008")
print()
import re
pattern = r"https?://[^\s]+"
Output:
Error Table:
Explanation:
pattern : r"https?://[^\s]+"
r – raw string
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")
Program:
print("Vaasita - AIE24008")
69
print()
import re
card="1234-4567-7890-0123"
Output:
Error Table:
Explanation:
[Link] the pattern to mask the last numbers except last four numbers.
r – raw string
\d{4}-\d{4}-\d{4} :
(\d{4}):
7. Write a program to Extract all words starting with a capital letter from the given text.
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"
Output:
Error Table:
Explanation:
pattern : r"\b[A-Z][a-zA-Z]*\b"
r – raw string
8. Write a regex to extract all PAN card numbers (format: 5 letters + 4 digits + 1 letter).
Example Domain
Program:
print("Vaasita - AIE24008")
print()
import re
pattern = r"\b[A-Z]{6}[0-9]{4}[A-Z]\b"
71
print("PAN Numbers:", pans)
Output:
Error Table:
Explanation:
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
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)
72
t=[Link](target=numbers)
[Link]()
[Link]()
Output:
Error table:
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)
def letters():
print(ch)
n=[Link](target=numbers)
t=[Link](target=letters)
73
[Link]()
[Link]()
[Link]()
[Link]()i
Output:
Error table:
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():
t = [Link](target=task, name="SuperThread")
[Link]()
74
[Link]()
Output:
Error table:
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)
[Link]()
[Link]()
Output:
75
Error table:
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.
Program:
print("Vaasita - 24008")
print()
import threading
def worker():
print("Running:", threading.current_thread().name)
t = [Link](target=worker, name=f"Worker-{i}")
[Link]()
[Link]()
Output:
76
Error table:
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.
Program:
print("Vaasita - 24008")
print()
def background():
for i in range(10):
[Link](1)
d = [Link](target=background, daemon=True)
[Link]()
[Link](3)
Output:
Error table:
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
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:
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]()
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:
1. Name Error: name 'l5' is not defined Ensure l5 is defined before it is used
inside details()
Explanation:
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")
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.
.get() fetches the current text entered into each Entry field.
[Link](...) updates the output label (l5) to display the formatted details.
Labels (Label) describe each input field: Name, Roll No, Email, Year of study.
9. [Link]()
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.
Program:
window = Tk()
80
[Link]("Calculator")
expression = ""
text_input = StringVar()
[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]()
frame2 = Frame(window)
[Link]()
frame3 = Frame(window)
81
[Link]()
frame4 = Frame(window)
[Link]()
frame5 = Frame(window)
[Link]()
frame6 = Frame(window)
[Link]()
[Link]()
OUTPUT:
Error Table:
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:
3. Entry field
o Creates an input field where the user sees numbers and operations.
4. Functions
1. press(num)
2. equalpress()
3. clear()
5. Button layout
83
Inside each row, creates a Button for each item:
o Otherwise, uses lambda x=b: press(x) to pass the button value to press().
6. Clear button
7. [Link]()
LAB-10
e. Print the first 300 characters of all visible text on the page.
g. All the main headings on the page (<h1>, <h2>, and <h3> tags)
i. All elements with the class name "menu" (print only their text content)
Program:
import requests
url = '[Link]
response = [Link](url)
84
[Link] = 'utf-8'
title_tag = [Link]
print("*******************************************")
first_paragraph = [Link]('p')
print("*******************************************")
all_links = soup.find_all('a')
href = [Link]('href')
text = link.get_text().strip()
print("*******************************************")
print("*******************************************")
print(page_text[:300])
print("*******************************************")
print("Main Headings:")
for h in headings:
print(h.get_text().strip())
print("*******************************************")
div_count = len(soup.find_all('div'))
print("*******************************************")
menu_elements = soup.find_all(class_='menu')
85
print(elem.get_text().strip())
Output:
86
Error table:
87
[Link] Happens if the website is down, or there’s no internet
connection. Fix: Check your internet or try another URL.
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
Parse HTML
Extract Hyperlinks
Extract Headings
88
● Finds all <h1>, <h2>, and <h3> tags.
Error Handling
a. The status code (e.g., 200 means success, 404 means not found)
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:
Explanation:
Import requests
url = '[Link]
response = [Link](url)
response.status_code
[Link]
[Link]('Server')
● Indicates the type of server hosting the page (e.g., Apache, nginx).
[Link]('Content-Type')
90
Print Encoding
[Link]
[Link].total_seconds()
[Link]
LAB-11
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("size:",[Link])
print("datatype:",[Link])
output:
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:
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))
output:
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:
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:
arr=[Link](12)
print("original array:",arr)
mat= [Link](3,4)
print("reshaped 3x4:\n",mat)
print("flattend array:",flat)
output:
v_stack=[Link]((arr2,arr3))
h_stack=[Link]((arr2,arr3))
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:
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:
Array Attributes:
Arithmetic Operations:
● Element-wise addition, subtraction, multiplication, and division are performed between arr2 and arr3.
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:
○ Column-wise (axis=0).
○ Row-wise (axis=1).
97
● This demonstrates NumPy’s ability to perform grouped data calculations.
● Trigonometric functions ([Link](), [Link](), [Link]()) are applied on the radian values.
● For 2D array: specific rows, columns, and sub-matrices are accessed using slicing (arr2[row, column]).
● Two arrays x and y are compared using relational operators (==, >, <).
● Arrays are combined vertically using [Link]() and horizontally using [Link]().
Advanced Operations:
LAB – 12
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:
Programs:
Code:
df=pd.read_csv(r'C:\Users\vaasi\Downloads\archive\[Link]')
df
Output:
99
2.
Code:
print([Link]())
100
print([Link]())
print([Link]())
101
print([Link]())
102
3.
Code:
print([Link])
print([Link])
103
print("*****multiple columns*****\n", df[['Id', 'Model','Price','Weight','cc']])
[Link][1]
104
[Link][1]
105
[Link][1:3]#slicing row 1 to 2
print([Link][0])#row by position
print([Link][0])#row by label
106
print([Link][:,1])#all rows, second column
107
[Link][0,'Fuel_Type'] # accesing a particular cell in this row-0 and column is fuel type
108
Filtering Data
109
4.
Code:
df['Hike_amount']
110
df['Total_price']
Inplace
[Link]
[Link]('Total_price',axis=1,inplace=True)
[Link](1,axis=0,inplace=True)
[Link]
111
5.
112
113
print([Link](0,inplace=True)) # Replace NaN with 0
print([Link]().sum()) # verifying the data frame after replacing the NaN with 0
114
115
[Link]
print(grouped)
6.
Code:
df.sort_values(by='Price',ascending=False,inplace=True)
df
116
7.
print(merged)
#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.
117
Data Visualization
Programs:
import pandas as pd
[Link]('Price')
[Link]('Frequency')
[Link]()
Output:
118
2. Univariate analysis -> histplot in seaborn
import pandas as pd
[Link]()
Output:
import pandas as pd
[Link]()
Output:
119
[Link] analysis using scatter plot
[Link](figsize=(8,5))
[Link]('Price')
[Link]()
Output:
120
[Link](x='Age_08_04', y='Price', data=df, hue='Fuel_Type', style='Automatic', palette='Set2')
[Link]()
Output:
# 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]()
output:
[Link] analysis
[Link]()
Output:
122
Visualization of correlations between numerical variables using a heatmap ([Link]()).
[Link](figsize=(10,7))
corr = [Link](numeric_only=True)
[Link]()
output:
123
Representation of aggregated or summarized data using a barplot ([Link]()).
avg_price = [Link]('Fuel_Type')['Price'].mean().reset_index()
[Link]()
output:
124
[Link](x='Automatic', y='Price', data=df, palette='flare')
[Link]()
output:
125
Saving a plot or visualization using [Link]().
[Link](figsize=(8,5))
[Link]('C:\Users\chikk\python_codes\image,png', dpi=300)
[Link]()
Error Table:
126
no attribute '...' method name
Explanation:
Pandas:
Data Visualization:
127