0% found this document useful (0 votes)
7 views

Python_Lab Manual AL-306

The document outlines the syllabus and objectives for the Computer Workshop/Introduction to Python-I course at Acropolis Institute of Technology and Research for the academic year 2024-2025. It includes details on laboratory practices, programming concepts, and specific experiments to be conducted, focusing on Object-Oriented Programming and Python programming skills. Additionally, it provides general instructions, hardware and software requirements, and references for further reading.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python_Lab Manual AL-306

The document outlines the syllabus and objectives for the Computer Workshop/Introduction to Python-I course at Acropolis Institute of Technology and Research for the academic year 2024-2025. It includes details on laboratory practices, programming concepts, and specific experiments to be conducted, focusing on Object-Oriented Programming and Python programming skills. Additionally, it provides general instructions, hardware and software requirements, and references for further reading.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

2024-25

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

Class/Year/Sem: AL_S-1/2rd / 3th

ACROPOLIS INSTITUTE OF TECHNOLOGY & RESEARCH,


INDORE

[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.

Aditya Anant Patil B. TECH II-year, III-semester in the Computer

Workshop/Introduction to Python-I Laboratory of this institute during

the academic year 2024- 2025.

Signature of the Faculty

2
ABOUT THE LABORATORY

In this lab, students will be able to learn and practice Computer


Workshop/Introduction to Python-I (AL-306) concepts. Students can
expand their skill set by getting hands-on experience on various Object
Oriented concepts. The concepts & hands-on experience discussed in this
lab focuses on various data structures and inbuilt classes, libraries of
Python.
The outcome of this lab is to make students understand the structure,
utility and technologies for Python programming language.

3
GENERAL INSTRUCTIONS FOR LABORATORY CLASSES

 DO’S

 Without Prior permission do not enter into the Laboratory.

 While entering into the LAB students should wear their ID cards.

 The Students should come with proper uniform.

 Students should sign in the LOGIN REGISTER before entering into the
laboratory.

 Students should come with observation and record note book to the laboratory.

 Students should maintain silence inside the laboratory.

 After completing the laboratory exercise, make sure to shutdown the system
properly.

 DONT’S

 Students bringing the bags inside the laboratory.

 Students using the computers in an improper way.

 Students scribbling on the desk and mishandling the chairs.

 Students using mobile phones inside the laboratory.

 Students making noise inside the laboratory.

4
SYLLABUS
Course: AL306 Computer Workshop/Introduction to Python-I
Branch/Year/Sem: Artificial Intelligence & Machine Learning / II / III

Module1: Introduction to python language, Basic syntax, Literal Constants, Numbers,


Variable and Basic data types, String, Escape Sequences, Operators and Expressions,
Evaluation Order, Indentation, Input, Output, Functions, Comments.

Module2: Data Structure: List, Tuples, Dictionary, DataFrame and Sets, constructing,
indexing, slicing and content manipulation.

Module3: Control Flow:Conditional Statements - If, If-else, Nested If-else. Iterative


Statement - For, While, Nested Loops. Control statements - Break, Continue, Pass.

Module4: Object oriented programming:Class and Object, Attributes, Methods,


Scopes and Namespaces, Inheritance, Overloading, Overriding, Data
hiding,Exception: Exception Handling, Except clause, Try finally clause, User
Defined Exceptions.

Module5: Modules and Packages: Standard Libraries: File I/0, Sys, logging, Regular
expression, Date and Time, Network programming, multi-processing and multi
threading.

References

 Timothy A. Budd: Exploring python, McGraw-Hill Education.

 R. NageshwarRao, “Python Programming”, Wiley India

 Think Python: Allen B. Downey, O'Reilly Media, Inc.

5
HARDWARE AND SOFTWARE REQUIREMENTS:

S. No. Name of Item Specification

1 Computer System Hard Disk min 5 GB


RAM: 4 GB / 8 GB
Processor: Intel i3 or above

S. No. Name of Item Specification

1 Operating system Windows X/ Linux


Software and Editor Python 3.x.x

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 AND OUTCOMES

 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.

2 Write a Python program for command line arguments.

3 Write various Python programs demonstrating use of If,


If-else, Nested If-else.
4 Write various Python programs demonstrating use of
For, While, Nested Loops.
5 Write Python programs using Control statements -
Break, Continue, Pass.
6 Write Python programs using List with its different
methods.
7 Write Python programs using Set with its different
methods.

8 Write Python programs using Tuple with its different


methods.
9 Write Python programs using Dictionary with its
different methods.
10 Write Python program to demonstrate Classes and objects

11 Write Python program for Constructor and use of init


method.
12 Write Python program for different Inheritances and
differentiate Overloading and Overriding.

8
Program Outcome (PO)

The engineering graduate of this institute will demonstrate:


a) Apply knowledge of mathematics, science, computing and engineering fundamentals to computer
science engineering problems.
b) Able to identify, formulate, and demonstrate with excellent programming, and problem solving skills.
c) Design solutions for engineering problems including design of experiment and processes to meet
desired needs within reasonable constraints of manufacturability, sustainability, ecological,
intellectual and health and safety considerations.
d) Propose and develop effective investigational solution of complex problems using research
methodology; including design of experiment, analysis and interpretation of data, and combination of
information to provide suitable conclusion. synthesis
e) Ability to create, select and use the modern techniques and various tools to solve engineering problems
and to evaluate solutions with an understanding of the limitations.
f) Ability to acquire knowledge of contemporary issues to assess societal, health and safety, legal and
cultural issues.
g) Ability to evaluate the impact of engineering solutions on individual as well as organization in a
societal and environmental context, and recognize sustainable development, and will be aware of
emerging technologies and current professional issues.
h) Capability to possess leadership and managerial skills, and understand and commit to professional
ethics and responsibilities.
i) Ability to demonstrate the team work and function effectively as an individual, with an ability to
design, develop, test and debug the project, and will be able to work with a multi-disciplinary team.
j) Ability to communicate effectively on engineering problems with the community, such as being able
to write effective reports and design documentation.
k) Flexibility to feel the recognition of the need for, and have the ability to engage in independent and life-
long learning by professional development and quality enhancement programs in context of
technological change.
l) A practice of engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and entrepreneurship

9
EXPERIMENT 1 :

Write Python programs using primitive data types/classes: Integer, String with inputs and
different
output formatting.

# output formatting using f string

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

Type Casting--> is the way of converting data type of any variable.


two types of type casting: 1] implicit 2] explicit type casting

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)

print("Number of arguments passed:", len(sys.argv) - 1)


print("Arguments passed:", sys.argv[1:])

for i, arg in enumerate(sys.argv[1:], start=1):


print(f"Argument {i}: {arg}")

$ python command_line_args.py hello world 123


Number of arguments passed: 3
Arguments passed: ['hello', 'world', '123']
Argument 1: hello
Argument 2: world
Argument 3: 123

Experiment 3. Write various Python programs demonstrating use of If, If-else,


Nested If-else.

#program to accept username if user enter 1 else promt for taking user's address detail

a = input("Enter 1 to provide username or press anything else: ")


if a == "1":
username = input("Enter your username: ")
print("Username accepted:", username)
else:
address = input("Enter your address: ")
print("Address accepted:", address)

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

x = float(input("Enter the num1= "))


y = float(input("Enter the num2= "))
print(f'{x} is larger') if (x>y) else print(f'{y} is larger')

output

Experiment4. Write various Python programs demonstrating use of For, While, Nested
Loops.

# wap to print mult tables for prime numbers between 2 to 200

for n in range(2, 202):


prime = True
for i in range (2, int(n * 1/2) + 1):
if n % i == 0:
prime = False
break
if prime:
print(f"\n Product Table for {n}:")
for i in range(1, 11):
print(f"{n} x {i} = {i*n}")

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

# write a program for odd numbers sum upto 100

total = 0
for a in range(1,101):
if a%2==0:
continue
else:
total= total+a
print(f"total = {total}")

output

# wap to print multiple tables for prime numbers between 2 to 200

for n in range(2, 202):


prime = True
for i in range (2, int(n * 1/2) + 1):
if n % i == 0:
prime = False
break
if prime:
print(f"\n Product Table for {n}:")
for i in range(1, 11):
print(f"{n} x {i} = {i*n}")
output

15
Experiment 6. Write Python programs using List with its different methods.

# write a program to double each element of list using list comprehension


list1 = [1,2,3,4,5,6,7,8,9,10]
list2 = [ i*2 for i in list1]
print(list2)

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)

list1= [i for i in range(50) if i%3==0]


print(list1)

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)

l2 = [j for i in list1 for j in i]


16
print(l2)

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

a = [" hello this is a code for strip() function "]


print(a)
x = [i.strip() for i in a]
print(x)

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.

Using add() Method

fruits = {"apple", "banana", "cherry"}


fruits.add("orange")
print(fruits) # Output: {'apple', 'banana', 'cherry', 'orange'}

Using update() Method

17
fruits = {"apple", "banana"}
fruits.update(["cherry", "orange", "apple"])
print(fruits)

Using remove() Method

fruits = {"apple", "banana", "cherry"}


fruits.remove("banana")
print(fruits)

Using discard() Method

fruits = {"apple", "banana", "cherry"}


fruits.discard("banana")
fruits.discard("mango")
print(fruits)

Using pop() Method

fruits = {"apple", "banana", "cherry"}


removed = fruits.pop()
print(f"Removed: {removed}")
print(fruits)

Using clear() Method

fruits = {"apple", "banana", "cherry"}


fruits.clear()
print(fruits)

Using union() Method

set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result)

Using intersection() Method


set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.intersection(set2)
print(result)

Using difference() Method

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.

my_tuple = (10, 20, 30, 40, 50)


#1
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])

output: First element: 10


Last element: 50

#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

def price(self, price):


selling_rate = self.currentprice = price

def calculate_value(self , age):


deprecriate = 0.10
self.resellingvalue = self.currentprice * (1 - (deprecriate*age))
return (self.resellingvalue)

def show(self, age):


resellingvalue = self.calculate_value(age)
print(f" vehicle is a {self.vehicletype}")
print(f" color of vehicle is {self.color}")
print(f" company of vehicle is {self.company}")
print(f" milage of vehicle is {self.milage}")
print(f" curent value od vehicle is {self.currentprice}")
print(f" reselling value of the vehicle is {self.resellingvalue}")

vehicle = vehicle("car", "orange", "jeep" , 50)


vehicle.price(2000000)
vehicle.show(5)

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")

class Eagle(Animal, Bird):


def speak(self):
print("Eagle screeches")

# 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

Difference between overloading and overriding

26

You might also like