Lab 1: Introduction to Python
1. What is Python?
Python is a high-level, interpreted, general-purpose programming language. It is easy to
learn because its syntax is simple and readable. Python is widely used in web
development, data science, artificial intelligence, machine learning, automation, and
software development.
--------------------------------------------------------------------------------------------------------------------
2. List the features of Python programming language.
Answer: The main features of Python are:
1. Easy to learn and use – Python has simple and readable syntax.
2. Interpreted language – Python programs are executed by an interpreter.
3. Dynamically typed – We don't need to declare the variable's data type.
4. Object-oriented – Python supports classes and objects.
5. Portable – Python programs can run on different operating systems.
6. Open source – Python is freely available.
7. Large library support – It provides many built-in and external libraries.
8. High-level language – It is closer to human language than machine language.
9. Supports multiple programming paradigms – It supports procedural, object-oriented,
and functional programming.
10. Extensible and embeddable – Python can work with programs written in other
languages.
3. State whether True or False. If False, give the correct answer.
a) Python is a statically typed language.
Answer: FALSE
Correct statement: Python is a dynamically typed language.
Example:
x = 10
print(x)
x = "Hello"
print(x)
Python automatically determines the type of x.
b) Python is both procedural as well as Object Oriented Language.
Answer: TRUE
Python supports both procedural programming and object-oriented programming.
Procedural example:
a = 10
b = 20
print(a + b)
Object-oriented example:
class Student:
def greet(self):
print("Hello")
s = Student()
[Link]()
c) Python is cross O.S compatible and portable.
Answer: TRUE
Python programs can generally run on different operating systems such as Windows, Linux, and
macOS, provided Python and any required dependencies are installed.
Example:
print("Python runs on different operating systems")
d) Python can be used for WEB Development using Django Framework.
Answer: TRUE
Django is a popular Python web framework used to develop web applications.
e) Pandas is a Python library used for working with data sets.
Answer: TRUE
Pandas is a Python library commonly used for data analysis and working with structured
datasets.
4. How to install additional library required by the Python program?
Answer:
Additional Python libraries can be installed using pip, which is Python's package installer.
The general command is:
pip install library_name
Example — installing Pandas:
pip install pandas
5. Define Data Science in simple words.
Answer:
Data Science is the process of collecting, cleaning, analyzing, and interpreting data to find useful
Example:
Suppose a school has students' marks from several years. Using Data Science, we could analyze
the marks to find:
Simple Python example:
marks = [70, 80, 90, 60, 85]
average = sum(marks) / len(marks)
print("Average marks:", average)
Output:
Average marks: 77.0
Lab-3[Python Programming Basics]
Q.1 List various data types in python?
num1=45
print(num1," is a type of", type(num1))
num2=7.21
print(num2," is a type of", type(num2))
num3=6+5j
print(num3," is a type of", type(num3))
nm=’Soham’
print(nm," is a type of", type(nm1))
flag=True
print(flag," is a type of", type(flag))
collection1=[6,8,7,3]
print(collection1," is a type of", type(collection1))
collection2=(3,7,6,21)
print(collection2," is a type of", type(collection2))
collection3={6,9,3,6,3}
print(collection3," is a type of", type(collection3))
collection4={1:RWD,2:'python'}
print(collection4," is a type of", type(collection4))
--------------------------------------------------------------------------------------------------------------------------
Q.2 Area of right angled triangle Print the output in various print details
height=float(input("Enter the height for right angle triangle "))
base=float(input("Enter the base for right angle triangle "))
area=0.5*height*base
print("Area of right angle triangle",area)
print("Area =%f"%area)
print("area = {}".format(area))
print(f"area = {area}")
print(f'area={area:.2f}')
--------------------------------------------------------------------------------------------------------------------------
Q.3Calculate salary details & print the details calculate gross salary and net salary
empname=input('enter name')
designation=input('enter designation')
department=input('enter department')
sal=float(input('enter basic salary'))
DA=sal*0.05
HRA=sal*0.03
PF=750
IT=sal*0.07
gross= sal+HRA+DA
net_sal=gross-PF-IT
print('Employee Name :',empname,'\nDesignation :',designation)
print('Department :',department,'\nSalary :',sal)
print(f'DA - {DA} HRA - {HRA} IT - {IT} PF - {PF}')
print('Net Salary - ',net_sal)
------------------------------------------------------------------------------------------------------------------------------
Q.4 display area , diameter and circumference of a circle
radius=float(input('enter the radius'))
da=2*radius
area=3.14*radius*radius
circum=2*3.14*radius
print(f'diameter ={da}')
print('area = ',area)
print('circumference ={}'.format(circum))
---------------------------------------------------------------------------------------------------------------------
Q.5 Accept the student details and marks, calculate the total and average marks
studname=input('enter your name ')
m = float(input("enter marks for math: "))
e = float(input("enter marks for english: "))
s = float(input("enter marks for science: "))
total=m+e+s
average=total/3
print('Student Name - ',studname)
print(f'Marks: Maths - {m} English - {e} Science - {s}')
print('Total - {0} Average - {1}'.format(total,average))
Lab-4[Handling String in Python]
Q.1Count the number of non-vowels characters in the string
s1=input("Enter a string : ")
vowels='aeiouAEIOU'
count=0
for ch in s1:
if [Link]() and ch not in vowels:
count=count+1
print('number of non vowels characters :',count)
-------------------------------------------------------------------------------------------------------------------------------
Q.2 Calculte the length of the string without using any built in function
s2=input('enter a string : ')
c1=0
for ch in s2:
c1=c1+1
print('length of the string : ',c1)
----------------------------------------------------------------------------------------------------------------------------
Q.3 count the number of words in given string
s3=input('enter the strings : ')
list1=[Link]()
size=len(list1)
print('Number of words : ',size)
----------------------------------------------------------------------------------------------------------------------------
Q. 4 to count the input string in capital letter and vice-versa
string1=input('enter a name : ')
print('lower case = ',[Link]())
print('upper case = ',[Link]())
------------------------------------------------------------------------------------------------------------------------------
Q.5 To check if given word is present in the input string
string2=input('enter string : ')
str= 'seed'
flag= str in string2
if flag:
print(str,' is present in',string2)
else :
print(str,'is not present in ',string2)
Lab-5[Python Data types -List, Tuple, Set, Dictionary]
Q.1 Program to sum all the items in a list
items=[5,6,9,3,4,8]
sum=0
for no in items:
sum=sum+no
print("Addition of all elements are : ",sum)
-----------------------------------------------------------------------------------------------------------------------------
Q.2 Program to remove the duplicate from list
lst = [5,9,5,6,9,7,3,7]
newlist = []
for i in lst:
flag = False
for j in newlist:
if i == j:
flag = True
break
if not flag:
[Link](i)
print("list after removing duplicates:", newlist)
-------------------------------------------------------------------------------------------------------------------------------
Q.3 Check given element is available in the list of strings
names=['sayali','trupti','suraj','sagar','swapnil']
givenname=input('Enter name :')
flag=False
for nm in names:
if(givenname==nm):
flag=True
print(givenname,' is present in list')
break
if(flag==False):
print(givenname,' is not present in list')
---------------------------------------------------------------------------------------------------------------------------
Q.4 find how many times an element occurs in the given list
elements=[10,25,66,25,15,48,25,10]
ele=int(input('Enter element :'))
count=0
for e in elements:
if(e==ele):
count+=1
print('element occurs',count,'times')
-----------------------------------------------------------------------------------------------------------------------------
Q.5 Create a dictionary of atleast 5 elements and display them
d1={1:'sayali',2:'meenal',3:'pooja',4:'swapnil',5:'trupti'}
print(d1)
for k,v in [Link]():
print(k," : ",v)
----------------------------------------------------------------------------------------------------------------------------
Q.6 find the size of a tuple
t1=(1,5,6,65,7,9,9)
print(t1)
print(len(t1))
cnt=0
for n in t1:
cnt+=1
print("length of tuple = ",cnt)
------------------------------------------------------------------------------------------------------------------------------
Q.7Maximum and minimum k elements in tuple
t1=(5,6,9,8,5,49,3,7)
print(max(t1))
print(min(t1))
minele=t1[0]
maxele=t1[0]
for n in t1:
if(minele>n):
minele=n
elif(maxele<n):
maxele=n
print("minimum element - ",minele)
print("maximum element - ",maxele)
-----------------------------------------------------------------------------------------------------------------------------
Q.8
matrix=[
[1,2,3],
[4,5,6],
[7,8,9]
]
li=[]
for r in matrix:
sum=0
for c in r:
sum=sum+c
[Link](sum)
print(li)
Lab-6 [Functions, Modules, Packages]
[Link] area of rectangle.
def find_area_rect(n1,n2):
area = n1*n2
return area
try :
print("Enter length :")
length=int(input())
print("Enter breadth")
breadth = int(input())
area_rect = find_area_rect(length,breadth)
print("Area of Rectangle:",area_rect)
except ValueError:
print("Invalid input! Please enter numeric values only.")
------------------------------------------------------------------------------------------------------------------------------
[Link] area,diameter,circumference of circle.
def operations_circle(radius):
area= 3.14 * radius * radius
diameter = 2 * radius
circumference = 2 * 3.14 * diameter
return area, diameter, circumference
try:
print("Enter radius :")
radius=int(input())
circle_area, circle_dia,circle_circum = operations_circle(radius)
print("Circle Operations:")
print("area : ",circle_area)
print("Diameter:",circle_dia)
print("Circumference:",circle_circum)
except ValueError:
print("Invalid input! Please enter numeric values only.")
[Link] list of numbers that vary in each call as input and output a list that holds square of
each element.
def find_square(list_num):
output_list=[]
for x in list_num:
result = x * x
output_list.append(result)
print("output list:",output_list)
print("Enter number of elements to input")
number = int(input())
list_num=[]
for n in range(number):
num = int(input("Enter element:"))
list_num.append(num)
print("Input list:",list_num)
find_square(list_num)
-----------------------------------------------------------------------------------------------------------------------------
[Link] a string in any charcter case and determine the number of words in given input
String.
def count_words(text):
words = [Link]()
print('Words:',words)
return len(words)
print("Enter a String to find no of words in a string:")
input_string = input()
word_count= count_words(input_string)
print("Number of words :",word_count)
----------------------------------------------------------------------------------------------------------------------------
[Link] varying number of numerical values and return their sum and average.
def find_sum_avg(*x):
sum = 0
for num in x:
sum = sum +num
avg = sum/len(x)
return sum,avg
sum,avg = find_sum_avg(2,3,4)
print ("Sum:",sum)
print("Average:",avg)
------------------------------------------------------------------------------------------------------------------------------
Q.6. Create a module name GeometricalShapes that holds multiple functions to calculate the
area as square, rectangel , circle.
Step 1: Create [Link]
----In the same folder as your main program, create a file named exactly:
[Link]
Put this inside:
import math
def area_square(length):
return length * length
def area_rectangle(width, breadth):
return width * breadth
def area_circle(radius):
return [Link] * radius * radius
[Link]
from GeometricalShapes import *
print("Enter length for square:")
length = int(input())
print("Area of square :",area_square(length))
print("Enter width & breadth for Rectangle")
width=int(input())
breadth =int(input())
print("Area of Rectangle :",area_rectangle(width,breadth))
print("Enter radius for Circle")
radius=int(input())
print("Area of Circle :",area_circle(radius))
How to run – using command line
F:\>cd python
F:\python>[Link]
Enter length for square:
2
Area of square : 4
Enter width & breadth for Rectangle
6
3
Area of Rectangle : 18
Enter radius for Circle
3
Area of Circle : 28.274333882308138
------------------------------------------------------------------------------------------------------------------
Q.7. create a module named temperatures that has function to convert Celsius temp to
Fahrenheit temp and Fahrenheit temp to Celsius temp
1. Create [Link]
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
2. Create [Link]
Use the module like this:
import temperatures
c = float(input("Enter temperature in Celsius: "))
print("Temperature in Fahrenheit:", temperatures.celsius_to_fahrenheit(c))
f = float(input("Enter temperature in Fahrenheit: "))
print("Temperature in Celsius:", temperatures.fahrenheit_to_celsius(f))
---------------------------------------------------------------------------------------------------------------------------
Q.8. create a module named convert_units that has a function to convert Km to ms
and convert min to hours
1. Create convert_units.py
def km_to_m(km):
return km * 1000
def min_to_hours(minutes):
return minutes / 60
2. Create [Link]
import convert_units
km = float(input("Enter distance in kilometers: "))
print("Distance in meters:", convert_units.km_to_m(km))
minutes = float(input("Enter time in minutes: "))
print("Time in hours:", convert_units.min_to_hours(minutes))
LAb-7 [OOP]
[Link] a class Course
class Course:
courseAbbr=None
courseName=None
courseTech=None
startDate=None
fees=None
venue=None
def __init__(self,courseAbbr,courseName,courseTech,startDate,fees,venue):
[Link]=courseAbbr
[Link]=courseName
[Link]=courseTech
[Link]=startDate
[Link]=fees
[Link]=venue
def __str__(self):
res = "Abbr: " + [Link] + "\t Name: " + [Link] + "\t Tech: " +
[Link]
res += "\t StartDate: " + [Link] + "\t Fees: " + str([Link]) + "\t Venue: " +
[Link]
return res
c=Course('FSD','Full Stack Developer','python, java, sql','1-april-26',25000,'Pune')
print(c)
------------------------------------------------------------------------------------------------------------------------------
Q.2. Create class participant that inherits the Course class
class Course:
courseAbbr=None
courseName=None
courseTech=None
startDate=None
fees=None
venue=None
def __init__(self,courseAbbr,courseName,courseTech,startDate,fees,venue):
[Link]=courseAbbr
[Link]=courseName
[Link]=courseTech
[Link]=startDate
[Link]=fees
[Link]=venue
def __str__(self):
res = "Abbr: " + [Link] + "\t Name: " + [Link] + "\t Tech: " +
[Link]
res += "\t StartDate: " + [Link] + "\t Fees: " + str([Link]) + "\t Venue: " +
[Link]
return res
class Participant(Course):
enrollNo=None
fullName=None
gender=None
contactNo=None
def
__init__(self,courseAbbr,courseName,courseTech,startDate,fees,venue,enrollNo,fullName,gen
der,contactNo):
super().__init__(courseAbbr,courseName,courseTech,startDate,fees,venue)
[Link]=enrollNo
[Link]=fullName
[Link]=gender
[Link]=contactNo
def show(self):
res = "Abbr: " + [Link] + "\t Name: " + [Link] + "\t Tech: " +
[Link]
res += "\t StartDate: " + [Link] + "\t Fees: " + str([Link]) + "\t Venue: " +
[Link]
res += "\t EnrollNo: " + str([Link]) + "\t FullName: " + [Link] + "\t Gender: " +
[Link] + "\t ContactNo: " + str([Link])
return res
partObj=Participant("JFSD","Java","Java devlopment","05 Jan
2026",50000,"Pune",102,"Xyz","Female",12345666)
print([Link]())
-----------------------------------------------------------------------------------------------------------------------------
Q.3. create calculator class
class Calculator:
@staticmethod
def add(x,y):
return x+y
@staticmethod
def subtract(x,y):
return x-y
@staticmethod
def multiply(x,y):
return x*y
@staticmethod
def divide(x,y):
return x/y
result=[Link](10,20)
print("Sum=",result)
result=[Link](50,20)
print("Subtraction=",result)
result=[Link](10,20)
print("Multiplication=",result)
result=[Link](500,13)
print(f"Division={result}")
------------------------------------------------------------------------------------------------------------------------
Q.4. create an abstract class name Details. It sholud have an abstrcat that displays details.
Create 2 child class that implements the abstract class
from abc import ABC, abstractmethod
# Abstract Class
class Details(ABC):
@abstractmethod
def display(self):
pass
# Child Class 1
class Student(Details):
def __init__(self, name, roll_no):
[Link] = name
self.roll_no = roll_no
def display(self):
print(f"Student Name: {[Link]}\t Roll No: {self.roll_no}")
# Child Class 2
class Employee(Details):
def __init__(self, emp_name, emp_id):
self.emp_name = emp_name
self.emp_id = emp_id
def display(self):
print(f"Employee Name: {self.emp_name}\t Employee ID: {self.emp_id}")
s = Student("Sayali", 1001)
e = Employee("Rahul", 5001)
[Link]()
[Link]()
-------------------------------------------------------------------------------------------------------------------------------
[Link] an python class that illustrate the use of instance variable, instance methods,along
with class variable and methods."""
class Student:
# Class Variable
school_name = "ABC College"
def __init__(self, name, marks):
[Link] = name # Instance Variable
[Link] = marks # Instance Variable
# Instance Method
def display(self):
print(f"Name: {[Link]}\t Marks: {[Link]}\t School: {Student.school_name}")
# Instance Method
def update_marks(self, new_marks):
[Link] = new_marks
# Class Method
@classmethod
def change_school(cls, new_name):
cls.school_name = new_name
s1 = Student("Sayali", 85)
s2 = Student("Rahul", 90)
# Calling Instance Method
[Link]()
[Link]()
# Updating Instance Variable
s1.update_marks(95)
[Link]()
# Calling Class Method
Student.change_school("XYZ College")
# After changing class variable
[Link]()
[Link]()
Lab-8 [Exception Handling]
Q.1.
class Rectangle:
def __init__(self,length,breadth):
[Link]=length
[Link]=breadth
def calculate_area(self):
area= [Link] * [Link]
print("Area of rectangle:",area)
try:
x=int(input("Enter length"))
y=int(input("Enter breadth"))
rect=Rectangle(x,y)
rect.calculate_area()
except ValueError as e:
print("Value Error occurred",e)
except TypeError as e:
print("Type Error occurred",e)
-------------------------------------------------------------------------------------------------------------------------
Q.2.
class CustomError(Exception):
pass
class Circle:
def __init__(self,radius):
[Link]=radius
def calculate(self):
try:
if([Link]<0):
raise CustomError("Negative number is not allowed")
except CustomError as e:
print(f"Custom error: {e}")
else:
area=3.14*[Link]*[Link]
diameter= 2*[Link]
circumference=2*3.14*[Link]
print("area :",area,"\t diameter:",diameter,"\t circumference:",circumference)
circle= Circle(5)
[Link]()
==============================================================================
Lab-9 [File Handling]
Q.1. To read the entire text file and display its content
fp=""
try:
fp=open(r"D:\Python module\[Link]","r")
print([Link]())
except FileNotFoundError:
print("Please check the path")
finally:
[Link]()
--------------------------------------------------------------------------------------------------------------------------
Q.2 Append to the existing to the text file
fp=""
try:
fp=open(r"D:\Python module\[Link]","a")
[Link]("adding the new content")
except FileNotFoundError:
print("File Not found")
finally:
[Link]()
------------------------------------------------------------------------------------------------------------------------
Q.3 Accept count the no of lines in a file
fp=""
try:
fp = open(r"D:\Python module\[Link]", "r")
lines = [Link]()
print("Number of lines:", len(lines))
except FileNotFoundError:
print("File Not found")
finally:
[Link]()
-------------------------------------------------------------------------------------------------------------------------------
Q.4 to count how many times a given input word occurs in a text file
word = input("Enter word to search: ")
with open(r"D:\Python module\[Link]", "r") as fp:
text = [Link]()
count = [Link](word)
print("Occurrences:", count)
-------------------------------------------------------------------------------------------------------------------------------
Q.5 To list all sub directories and files for given folder
import os
path=r"D:\Python module"
items = [Link](path)
for item in items:
print(item)
=======================================================================
LAb -9 [Database Handling]
"""
create table student (
regno int auto_increment primary key,
name varchar(50),
gender varchar(50),
degree varchar(50),
passing_year int
);
"""
"""
create procedure getByRegNo(in rno int)
begin
select * from student where regno =rno;
end
"""
import [Link]
# database connection creation
def create_connection():
conn = [Link](
host="[Link]",
user="root",
password="Root@123",
port=3306,
auth_plugin='mysql_native_password',
use_pure=True,
database="test_db"
)
return conn
# insert
def insert_records(conn):
cursor = [Link]()
query = "insert into student (name, gender, degree,passing_year) values (%s, %s,%s,%s)"
values = [
("Amit","M","Bsc","2021"),
("Neha","F","Bcom","2022"),
("Rahul","M","Mcs","2023"),
("Smita","F","BBA","2024")
]
[Link](query, values)
[Link]()
print("Record inserted successfully")
[Link]()
[Link]()
# read
def read_records(conn):
cursor = [Link]()
query="select * from student"
[Link](query)
records=[Link]()
if records:
print(records)
else:
print("no records are found")
[Link]()
[Link]()
def execute_procedure(conn):
cursor = [Link]()
args = (6,)
[Link]("getByRegNo", args)
for result in cursor.stored_results():
data = [Link]()
if data:
for row in data:
print(row)
else:
print("No record found")
[Link]()
[Link]()
conn=create_connection()
##insert_records(conn)
##read_records(conn)
execute_procedure(conn)
LAb -10 [Advance language Features]
[Link] a program in Python to find whether the input contains only alphabets
(either capital or small) or it is alphanumeric only.
Ex:
print("Apple is red in color") # this is wrong string
print("Python_Exercises_1") # this is right string
import re
text=input("Enter text:")
pattern=r"[a-zA-Z_]+"
result=[Link](pattern,text)
if result:
print("It contains only aplhabets(capital or small)")
else:
print("It contains alphanumeric chars as well")
---------------------------------------------------------------------------------------------------------------------
[Link] find all words starting with the letter "a" in a given string.
pattern = r"\b[aA]\w+"
text="Apple is a fruit and apricot is another one and alomond is dry fruit."
matches=[Link](pattern,text)
print(matches)
--------------------------------------------------------------------------------------------------------------------
[Link] all positive elements from list using list comprehensiontechnique.
listnums=[12,-4,75,-35,-92,121,500,-235]
positive_num=[num for num in listnums if num>=0]
print(positive_num)
-----------------------------------------------------------------------------------------------------------------------------
[Link] a list containing only scripting language.
languages=['javascript','typescript','python','golang','vbscript']
script_lang=[lang for lang in languages if([Link](r"script$",lang))]
print(script_lang)
---------------------------------------------------------------------------------------------------------------------------
[Link] @capitalcase_decorator when applied to any function converts the
string parameter of target function to upper case letter.
def capitalcase_decorator(func):
def wrapper(word):
print("entered word:",word)
return func([Link]())
return wrapper
@capitalcase_decorator
def convert_to_upper(word):
return f"Upper cased word {word}"
print(convert_to_upper("apple"))
-------------------------------------------------------------------
Q6 find the square of each element in list.
numlist=[3,5,7,4,11,8]
square_num_list=[num*num for num in numlist]
print(square_num_list)
-------------------------------------------------------------------
[Link] all names that start with letter 'R'
names=["Arnavi","Raghav","Vrushabh","Rudransh","Reeva","Emma","Maira"]
new_names=[name for name in names if([Link](r"\AR",name))]
print(new_names)