Python_Lab Manual AL-306
Python_Lab Manual AL-306
Acropolis Institute of
Technology and
Research, Indore
Department of CSE
Submitted To: Dr. Pragya
Pandey (Artificial Intelligence & Machine
Learning)
Computer Workshop/Introduction to
Python-I (AL-306)
Submitted By: Aditya Anant Patil
Enrollment No: 0827AL231013
[LAB ASSIGNMENT Computer Workshop/Introduction to Python-I (AL-306). The objective of this laboratory work is to give
students the exposure to Object Oriented Concepts using Python and implementations. ]
1
Department of CSE (Artificial Intelligence & Machine Learning)
CERTIFICATE
This is to certify that the experimental work entered in this journal as per
the B. TECH. II-year syllabus prescribed by the RGPV was done by Mr.
2
ABOUT THE LABORATORY
3
GENERAL INSTRUCTIONS FOR LABORATORY CLASSES
DO’S
While entering into the LAB students should wear their ID cards.
Students should sign in the LOGIN REGISTER before entering into the
laboratory.
Students should come with observation and record note book to the laboratory.
After completing the laboratory exercise, make sure to shutdown the system
properly.
DONT’S
4
SYLLABUS
Course: AL306 Computer Workshop/Introduction to Python-I
Branch/Year/Sem: Artificial Intelligence & Machine Learning / II / III
Module2: Data Structure: List, Tuples, Dictionary, DataFrame and Sets, constructing,
indexing, slicing and content manipulation.
Module5: Modules and Packages: Standard Libraries: File I/0, Sys, logging, Regular
expression, Date and Time, Network programming, multi-processing and multi
threading.
References
5
HARDWARE AND SOFTWARE REQUIREMENTS:
RATIONALE:
The purpose of this subject is to study the fundamental strengths and limits of cloud
services as well as how these interact with our system, computer science, and other
disciplines.
Course Objectives
The objective of this course is to enable students in developing understanding of the
principles of Object-Oriented Programming (OOP): classes, objects, inheritance,
polymorphism, encapsulation, and abstraction. Also, students must be able to develop
Python programs using OOP techniques to solve real-world problems.
Course Outcomes
CO1: Demonstrate a clear understanding of basic Python programming concepts, including
data types, variables, operators, loops, and control structures.
CO2: Apply these concepts to write simple Python programs for solving basic
computational problems.
CO3: Develop the ability to work with Python's built-in data structures such as lists, tuples,
sets, and dictionaries.
CO4: Utilize appropriate data structures to solve problems related to data manipulation
and storage efficiently.
CO5: Apply file handling techniques using File I/0, Sys, logging in Python programs.
6
7
Index
Grade &
Date of Pag Date of
S.No Name of the Experiment Sign of the
Exp. e Submission Faculty
No
.
1 Write Python programs using primitive data
types/classes: Integer, String with inputs and different
output formatting.
8
Program Outcome (PO)
9
EXPERIMENT 1 :
Write Python programs using primitive data types/classes: Integer, String with inputs and
different
output formatting.
print("hello")
print('A','B','C',sep='%')
a = 10
b = 20
c = b-a
print("c",c)
print(f"c = {c}")
OUTPUT
# simple calculations
P=100
R=2
T=10
SI=(P*R*T)/100
print(SI)
x=10
y=20
print(f"value of x={x},y={y},sep='%'")
Output
a=100
print(type(a))
b=55.4
print(type(b))
10
c=a+b
print(c)
print(type(c))
a="45"
b="50"
c=a+b
c=int(a)+int(b)
print(c)
Output
#Literals
# 1] Character Literal->
# 2] String Literal->
a='First Example'
b="Second Example"
c='''Third Example'''
print(c)
Output
# 3]Numeric Literals->
a=3+5j
print(a)
Output
# 4] Boolean Literals->
a = True
b = False
c = a + 50
d = b + 40
print(c)
print(d)
Output
11
Experiment 2. Write a Python program for command line arguments.
import sys
if len(sys.argv) < 2:
print("Usage: python program_name.py <arg1> <arg2> ... <argN>")
sys.exit(1)
#program to accept username if user enter 1 else promt for taking user's address detail
Output
#if else
marks = int(input("Enter the marks "))
if (marks >= 90):
a ="A"
#print("Grade obtained is A")
elif (marks >= 85 and marks<90):
a = "B"
12
#print("Grade obtained is B")
elif (marks >= 75 and marks<85):
a = "C"
#print("Grade obtained is C")
else:
a = "not qualified"
#print("not eligible")
print(f"Grade obtained is {a}")
output
# Ternary Statement -> statement when true if condition else condition when false
output
Experiment4. Write various Python programs demonstrating use of For, While, Nested
Loops.
output
13
#wap to print all even number between 1 to 100 in reverse order
for a in range(100,0,-1):
if a%2==0:
print(a,"is even")
else:
continue
output
Experiment 5. Write Python programs using Control statements - Break, Continue, Pass.
# write a program for odd numbers sum upto 100 with using pass
total = 0
for a in range(1,101):
if a%2==0:
pass
else:
print(f"a is {a}")
total= total+a
print(f"total = {total}")
14
output
total = 0
for a in range(1,101):
if a%2==0:
continue
else:
total= total+a
print(f"total = {total}")
output
15
Experiment 6. Write Python programs using List with its different methods.
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
#create a list by calculating sq of each element with and without using list comprehension
list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = [ i*i for i in list1]
print(list2)
list3 = []
for i in list1:
n = i*i
list3.append(n)
print(list3)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]
platening a list
# list of list having 3 elements each in the given 4 lists create a list having all elements
list1 = []
for i in range(4):
sublist = []
for j in range(3):
sublist.append(j)
list1.append(sublist)
print(list1)
Output:
[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
# create a list of negative elements and use list comprehension to create absolute elements
a = [-1,-2,-3,-4,-5]
print(a)
print(type(a))
b = [abs(i) for i in a]
print(b)
output:
[-1, -2, -3, -4, -5]
<class 'list'>
[1, 2, 3, 4, 5]
# create a list with spaces and then use strip() to remove the spaces
Output:
[' hello this is a code for strip() function ']
['hello this is a code for strip() function']
Experiment 7. Write Python programs using Set with its different methods.
17
fruits = {"apple", "banana"}
fruits.update(["cherry", "orange", "apple"])
print(fruits)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result)
set1 = {1, 2, 3, 4}
18
set2 = {3, 4, 5, 6}
result = set1.difference(set2)
print(result)
EXPERIMENT 8. Write Python programs using Tuple with its different methods.
#2
count_20 = my_tuple.count(20)
print("Count of 20 in tuple:", count_20)
output:
Count of 20 in tuple: 1
#3
index_of_30 = my_tuple.index(30)
print("Index of 30 in tuple:", index_of_30)
output:
Index of 30 in tuple: 2
#4
sliced_tuple = my_tuple[1:4]
print("Sliced tuple:", sliced_tuple)
Output:
Sliced tuple: (20, 30, 40)
#5
length_of_tuple = len(my_tuple)
print("Length of the tuple:", length_of_tuple)
Output:
Length of the tuple: 5
#6
19
another_tuple = (60, 70, 80)
concatenated_tuple = my_tuple + another_tuple
print("Concatenated tuple:", concatenated_tuple)
Output:
Concatenated tuple: (10, 20, 30, 40, 50, 60, 70, 80)
#7
repeated_tuple = my_tuple * 2
print("Repeated tuple:", repeated_tuple)
Output:
Repeated tuple: (10, 20, 30, 40, 50, 10, 20, 30, 40, 50)
EXPERIMENT 9. Write Python programs using Dictionary with its different methods.
#1 list with elements 1 to 5 create dict that will have list elements as numbers and cube of every number
list = [1,2,3,4,5]
print(list)
dict = {i: i**3 for i in list}
print(dict)
Output:
[1, 2, 3, 4, 5]
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
#2 create one dict value 100 to 104 and values 1 to 5 and replace value of 101 to 5000 use of methods value
pop and pop item
dict = {}
for i in range(100, 105):
a = input("enter values {i}: ")
dict[i]=a;
dict[101]= 5000
print(dict)
Output:
enter values {i}: 101
enter values {i}: 102
enter values {i}: 103
enter values {i}: 104
enter values {i}: 105
{100: '101', 101: 5000, 102: '103', 103: '104', 104: '105'}
20
#3
Using keys() Method
person = {"name": "Alice", "age": 25, "profession": "Engineer"}
keys = person.keys()
print(keys)
Output:
dict_keys(['name', 'age', 'profession'])
#4
Using values() Method
person = {"name": "Alice", "age": 25, "profession": "Engineer"}
values = person.values()
print(values)
Output:
dict_values(['Alice', 25, 'Engineer'])
#5
Using items() Method
person = {"name": "Alice", "age": 25, "profession": "Engineer"}
items = person.items()
print(items)
Output:
dict_items([('name', 'Alice'), ('age', 25), ('profession', 'Engineer')])
#6
Using get() Method
person = {"name": "Alice", "age": 25}
print(person.get("name"))
print(person.get("profession", "Not specified"))
Output:
Alice
Not specified
#7
Using update() Method
person = {"name": "Alice", "age": 25}
updates = {"age": 26, "profession": "Engineer"}
person.update(updates)
print(person)
Output:
{'name': 'Alice', 'age': 26, 'profession': 'Engineer'}
21
Experiment 10: Write Python program to demonstrate Classes and objects
#1
class sample_class:
i = 5 #data member
def sample_function(self):
print("hello")
obj1 = sample_class()
print(obj1.sample_function())
output:
hello
#2
class student:
name = (input("enter your name here "))
section = (input("enter the section "))
def print_student(self):
print(self.name)
print("section is = ", self.section)
student1 = student()
student1.print_student()
print(student1.name)
output:
enter your name here aditya
enter the section 2
aditya
section is = 2
#3
class employee:
def __init__(self, name , role):
self.name = name
self.role = role
def show(self):
print("role of employee = ", self.name ,"is", self.role)
22
emp1 = employee('satish', 'manager')
emp1.show()
output:
role of employee = satish is manager
Experiment 11: Write Python program for Constructor and use of init method.
#1
define class for vehicle having four instance variable vehicle type, color , company and milage write two
methods first two define price define reselling price and show method to print vehicle age along with current
price.
class vehicle:
def __init__(self, vehicle_type, color, company, milage ):
self.vehicletype = vehicle_type
self.color = color
self.company = company
self.milage = milage
self.currentprice = 0
23
output:
vehicle is a car
color of vehicle is orange
company of vehicle is jeep
milage of vehicle is 50
curent value od vehicle is 2000000
reselling value of the vehicle is 1000000.0
Experiment 12: Write Python program for different Inheritances and differentiate
Overloading and Overriding.
# Single Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
# Multiple Inheritance
class Bird:
def fly(self):
print("Bird can fly")
# Multilevel Inheritance
class Vehicle:
def move(self):
print("Vehicle moves")
class Car(Vehicle):
def move(self):
print("Car drives")
class ElectricCar(Car):
def move(self):
print("Electric car drives silently")
# Hierarchical Inheritance
24
class Employee:
def work(self):
print("Employee works")
class Manager(Employee):
def work(self):
print("Manager manages projects")
class Developer(Employee):
def work(self):
print("Developer writes code")
# Demonstrating Inheritance
# Single Inheritance
print("Single Inheritance:")
dog = Dog()
dog.speak()
# Multiple Inheritance
print("\nMultiple Inheritance:")
eagle = Eagle()
eagle.speak()
eagle.fly()
# Multilevel Inheritance
print("\nMultilevel Inheritance:")
ecar = ElectricCar()
ecar.move()
# Hierarchical Inheritance
print("\nHierarchical Inheritance:")
manager = Manager()
manager.work()
developer = Developer()
developer.work()
Output:
Single Inheritance:
Dog barks
Multiple Inheritance:
Eagle screeches
Bird can fly
Multilevel Inheritance:
Electric car drives silently
25
Hierarchical Inheritance:
Manager manages projects
Developer writes code
26