Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Python Lab Manual 24-25 - Final

The document is a laboratory manual for the Python Programming Lab (P2418103) at GEMS Polytechnic College, aimed at 2nd semester diploma students in Civil Engineering. It outlines the vision and mission of the institution and department, course outcomes, teaching and examination schemes, and provides a series of programming exercises for students to complete. The manual emphasizes practical skills in Python programming, including data types, control statements, and file operations.

Uploaded by

gaurav22ce45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python Lab Manual 24-25 - Final

The document is a laboratory manual for the Python Programming Lab (P2418103) at GEMS Polytechnic College, aimed at 2nd semester diploma students in Civil Engineering. It outlines the vision and mission of the institution and department, course outcomes, teaching and examination schemes, and provides a series of programming exercises for students to complete. The manual emphasizes practical skills in Python programming, including data types, control statements, and file operations.

Uploaded by

gaurav22ce45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

GPC/CIVIL/Python Programming Lab/P2418103

GEMS POLYTECHNIC COLLEGE


(Approved by AICTE, Govt. of India, F. No Northern/2015/1-2474317051)
NH-2, Jogiya More, Ratanpura, Aurangabad, Bihar – 824 121

P2418103 - PYTHON PROGRAMMING LAB

STATE BOARD OF TECHNICAL EDUCATION, BIHAR

2nd SEMESTER DIPLOMA IN CIVIL ENGG.

(Effective from Session 2024-2025)

LABORATORY MANUAL
Prepared By
Mr. Kumar. S,
Lecturer

GPC/IQAC/FORMAT/22 1 | Page
GPC/CIVIL/Python Programming Lab/P2418103

INDEX

Sl. No Content Page No

1. Vision & Mission of the Institution & Department 04

2. PEO, PO & PSO Statement 05

3. Teaching and Examinations Scheme 07

4. Course Outcomes & CO-PO/PSO Mapping 08

5. Experiments mapping with CO & Bloom’s Taxonomy 09

EX:1 Write and execute Python program to Calculate the Area


of a Triangle where its three sides a, b, c are given.
6. 10
s=(a+b+c)/2, Area=square root of s(s-a)(s-b)(s-c) (write
program without using function)
EX:2 Write and execute Python program to Swap Two
7. 12
Variables

EX:3 Write and execute Python program to Check if a Number


8. 13
is Positive, Negative or zero.

Ex:4 Write and execute Python program to Check whether the


9. 15
given year is a Leap Year

EX:5 Write and execute Python program to Reverse words in a


10. 17
given String in Python

EX:6 Write and execute Python program to Python program


11. 18
for removing i-th character from a string
EX:7 Write and execute Python program to find largest
12. 19
number in a given list without using max().
EX:8 Write and execute Python program to find the index of
13. 21
an item of a tuple

GPC/IQAC/FORMAT/22 2 | Page
GPC/CIVIL/Python Programming Lab/P2418103

14. EX:9 Write and execute Python program to to reverse a tuple. 22

EX:10 Write a Python function for calculating compound


15. 23
interest and call it.
EX:11 Write and execute Python program to demonstrate use
of following types of inheritance:

16. i. Single inheritance 25


ii. Multiple inheritance
iii. Multilevel inheritance

17. EX:12 Write Python program to demonstrate file operations. 28

Prepared By Verified By
Faculty In-charge HOD/Mech
GPC/IQAC/FORMAT/22 3 | Page
GPC/CIVIL/Python Programming Lab/P2418103

VISION OF GEMS POLYTECHNIC COLLEGE

Empowering the young minds with holistic education and futuristic skills to be a

valuable resource for the state and nation.

MISSION OF GEMS POLYTECHNIC COLLEGE

• To provide professional education thereby producing technically competent engineers

with moral and ethical values.

• To train students and provide them with leading resources to address problems faced

by industry and society.

• To encourage doers to embrace learning and achieve their personal best in building

their emotional, social and physical well-being.

VISION OF THE DEPARTMENT OF CIVIL ENGINEERING

Empowering the students in technical education and Excel those in the field of Civil

Engineering with concern of socio-economic development of region, state and nation.

MISSION OF THE DEPARTMENT OF CIVIL ENGINEERING

The Department of Civil Engineering is committed,

▪ To provide a platform for students to develop skills, knowledge, and wisdom

in various aspects of Civil Engineering.

▪ To inculcate ethical and moral values among the students.

▪ To encourage students to pursue higher education and take competitive exams.

GPC/IQAC/FORMAT/22 4 | Page
GPC/CIVIL/Python Programming Lab/P2418103

PROGRAM EDUCATIONAL OBJECTIVES (PEO)


PEO 1: To produce a diploma graduates with a strong foundation in subjects to pursue
a thriving professional to take part in providing a feasible solution for communal
problems related to Civil Engineering aspects.
PEO 2: To improve the capability of graduates to execute emerging techniques for
planning, analysis, design and execution of Civil Engineering projects through lifelong
learning.
PEO 3: To imbibe professional ethics to the graduates with a commitment to the society
and environment.

PROGRAM OUTCOMES (POs)


PO 1: Basic and Discipline specific knowledge:
Apply knowledge of basic mathematics, science and engineering fundamentals and
engineering specialization to solve the engineering problems.
PO 2: Problem analysis:
Identify and analyze well-defined engineering problems using codified standard
methods.
PO 3: Design/ development of solutions:
Design solutions for well-defined technical problems and assist with the design of
systems components or processes to meet specified needs.
PO 4: Engineering Tools, Experimentation and Testing:
Apply modern engineering tools and appropriate technique to conduct standard tests
and measurements.
PO 5: Engineering practices for society, sustainability and environment:
Apply appropriate technology in context of society, sustainability, environment and
ethical practices.
PO 6: Project Management:
Use engineering management principles individually, as a team member or a leader to
manage projects and effectively communicate about well-defined engineering
activities.

GPC/IQAC/FORMAT/22 5 | Page
GPC/CIVIL/Python Programming Lab/P2418103

PO 7: Life-long learning:
Ability to analyze individual needs and engage in updating in the context of
technological changes.

PROGRAM SPECIFIC OBJECTIVES (PSOs)

PSO 1: The graduates will proficiency in mathematics, basic science and engineering

fundamentals to excel in core areas of civil engineering.

PSO 2: The graduates will plan, analyse, design and prepare cost estimates for Civil

Engineering structures.

PSO 3: The graduates will able to apply technical and management skills for the

execution of work

GPC/IQAC/FORMAT/22 6 | Page
GPC/CIVIL/Python Programming Lab/P2418103

TEACHING AND EXAMINATIONS SCHEME

LABORATORY NAME Python Programming Lab

LABORATORY CODE P2418103

TEACHING
Periods per Week 04
SCHEME

Hours of Exam. 03

Internal(A) 20
Practical (ESE)
External(B) 30

EXAMINATION-
SCHEME Total Marks (A+B) 50

Pass Marks in the Subject 20

Credits 06

GPC/IQAC/FORMAT/22 7 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Course Outcomes
Upon completion of this course, the students can able to acquire the following
Practical Skills:

Course Outcomes:

CO103.1 Use various data types and operators in formation of expressions

CO103.2 Write and execute programs using control statements.

CO103.3 Perform relevant operations on Sequence data types

CO103.4 Create functions in modules


Use object-oriented approach and features in writing python
CO103.5
programs

CO103.6 Handle data files and exceptions.

CO – PO / PSO MAPPING
POs /
COs PO1 PO2 PO3 PO4 PO5 PO6 PO7 PSO1 PSO2 PSO3
PSOs

CO103.1 1 - 1 - - - - - - -

CO103.2 1 - 2 1 - - - - - -

CO103.3 1 - 2 1 - - - - - -

CO103.4 1 - 2 1 - - - - - -

CO103.5 1 - 2 1 - - - - - -

CO103.6 1 - 2 1 - - - - - -

GPC/IQAC/FORMAT/22 8 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Experiments mapping with CO & Bloom’s Taxonomy


Sl. No Content CO Bloom’s Level
1. EX:1 Write and execute Python program to Calculate the Area CO1 Ap
of a Triangle where its three sides a, b, c are given. s=(a+b+c)/2,
Area=square root of s(s-a)(s-b)(s-c) (write program without
using function)
2. EX:2 Write and execute Python program to Swap Two Variables CO1 Ap

3. EX:3 Write and execute Python program to Check if a Number CO2 Ap


is Positive, Negative or zero.

4. Ex:4 Write and execute Python program to Check whether the CO2 Ap
given year is a Leap Year

5. EX:5 Write and execute Python program to Reverse words in a CO2 Ap


given String in Python

6. EX:6 Write and execute Python program to Python program for CO2 Ap
removing i-th character from a string

7. EX:7 Write and execute Python program to find largest number CO3 Ap
in a given list without using max().
8. EX:8 Write and execute Python program to find the index of an CO3 Ap
item of a tuple
9. EX:9 Write and execute Python program to to reverse a tuple. CO3 Ap

10. EX:10 Write a Python function for calculating compound CO4 Ap


interest and call it.
11. EX:11 Write and execute Python program to demonstrate use of CO5 Ap
following types of inheritance:
i. Single inheritance
ii. Multiple inheritance
iii. Multilevel inheritance
12. EX:12 Write Python program to demonstrate file operations. CO6 Ap

Bloom’s Taxonomy Level

1 - Remembering 2- Understanding 3- Applying 4- Analysing 5- Evaluating 6- Creating

GPC/IQAC/FORMAT/22 9 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 1
Date:

Write and execute Python program to Calculate the Area of a Triangle


where its three sides a, b, c are given. s=(a+b+c)/2, Area=square root of s(s-
a)(s-b)(s-c) (write program without using function)

Aim:
To write and execute a Python program that calculates the area of a triangle
when the lengths of its three sides, aaa, bbb, and ccc, are given.

Heron's Formula:
1. Semi-Perimeter (s):

2. Area (A):

Where:
• a,b,a, b,a,b, and ccc are the lengths of the sides of the triangle.
• sss is the semi-perimeter.
• \sqrt{} denotes the square root function.

Program:
# Python Program to find the area of triangle

a=5
b=6
c=7

# Uncomment below to take inputs from the user


# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

GPC/IQAC/FORMAT/22 10 | Page
GPC/CIVIL/Python Programming Lab/P2418103

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Output

Result:

The program successfully calculates and displays the area of a triangle


based on the given side lengths.

GPC/IQAC/FORMAT/22 11 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 2
Date:

Write and execute Python program to Swap Two Variables

Aim:

To write and execute a Python program that swaps the values of two
variables.

Program:
# Define two variables with initial values
x = input("Enter the value of x: ")
y = input("Enter the value of y: ")

# Print original values


print(f"Before swapping: x = {x}, y = {y}")

# Swap the values using Python's tuple unpacking


x, y = y, x

# Print swapped values


print(f"After swapping: x = {x}, y = {y}")

Output:

Result:

The program successfully swaps the values of two variables and displays
the values before and after the swap.
GPC/IQAC/FORMAT/22 12 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 3
Date:

Write and execute Python program to Check if a Number is Positive,


Negative or zero.

Aim:
To write and execute a Python program that checks if a given number is
positive,
negative, or zero.

Program:
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

GPC/IQAC/FORMAT/22 13 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Output:

Result:

The program successfully checks and displays whether the entered number
is positive, negative, or zero based on the user input.

GPC/IQAC/FORMAT/22 14 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 4
Date:

Write and execute Python program to Check whether the given year
is a Leap Year.
Aim:
To write a program using a for loop that loops over a sequence

Program:

# Python program to check if year is a leap year or not

year = 2000

# To get year (integer input) from the user


# year = int(input("Enter a year: "))

# divided by 100 means century year (ending with 00)


# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))

# not divided by 100 means not a century year


# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))

# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))

GPC/IQAC/FORMAT/22 15 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Output:

Result:

The program using a for loop that loops over a sequence is executed
successfully.
GPC/IQAC/FORMAT/22 16 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 5
Date:

Write and execute Python program to Reverse words in a given String in


Python

Aim
To reverse the order of words in a given string.

Program:
def rev_words(string):
words = string.split(' ')
rev = ' '.join(reversed(words))
return rev

s= "Python is good"
print ("reverse: ",rev_words(s))

s2= "Hello from Study tonight"


print ("reverse: ",rev_words(s2))

Output:

Result:
The program reverses the order of words in the input string. The output is
"Python from World Hello".
GPC/IQAC/FORMAT/22 17 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 6
Date:

Write and execute Python program to Python program for removing


i-th character from a string

Aim:
To write and execute a Python program to remove the i-th character from
a given string.

Program:
s = "PythonProgramming"

# Index of the character to remove


i=6

# Removing i-th character


res = s[:i] + s[i+1:]
print(res)

Output:

Result:
To remove the i-th character from a string in one line: result = string[:i]
+ string[i+1:] if 0 <= i < len(string) else "Invalid position" You can replace
`string` and `i` with the appropriate values or variables.

GPC/IQAC/FORMAT/22 18 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 7
Date:

Write and execute Python program to Find the largest number


in a given list without using max()

Aim:
To find the largest number in a given list without using the built-in max()
function.

Program:
def find_largest_number(numbers):
if not numbers:
raise ValueError("The list is empty")

largest = numbers[0]
for num in numbers[1:]:
if num > largest:
largest = num
return largest

# Example usage
if __name__ == "__main__":
try:
input_list = list(map(int, input("Enter numbers separated by spaces:
").split()))
result = find_largest_number(input_list)
print(f"The largest number in the list is: {result}")
except ValueError as e:
print(f"Error: {e}")

GPC/IQAC/FORMAT/22 19 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Output:

Result:
The program successfully finds and prints the largest number in the list,
which is 98 in this case.
GPC/IQAC/FORMAT/22 20 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 8
Date:

Write and execute Python program to Find the index of an item in a tuple

Aim:
To find the index of a specific item in a tuple.

Program:
def find_index_in_tuple(tup, item):
try:
# Find and return the index of the item
return tup.index(item)
except ValueError:
# If the item is not in the tuple
return -1

# Example usage
if __name__ == "__main__":
input_tuple = tuple(input("Enter the elements of the tuple separated by
spaces: ").split())
search_item = input("Enter the item to find: ")
index = find_index_in_tuple(input_tuple, search_item)
if index != -1:
print(f"The index of '{search_item}' in the tuple is: {index}")
else:
print(f"'{search_item}' is not found in the tuple.")

Output:

Result:
The program successfully finds and prints the index of the specified item (`30`)
in the tuple, which is `2`.
GPC/IQAC/FORMAT/22 21 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 9
Date:

Write and execute Python program to Reverse a tuple

Aim:
To reverse the order of items in a tuple.

Program:
def reverse_tuple(tup):
return tup[::-1]

# Example usage
if __name__ == "__main__":
input_tuple = tuple(input("Enter the elements of the tuple
separated by spaces: ").split())
reversed_tuple = reverse_tuple(input_tuple)
print(f"The reversed tuple is: {reversed_tuple}")

Output:

Result:
The program successfully reverses and prints the tuple.

GPC/IQAC/FORMAT/22 22 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 10
Date:

Write and execute Python program to Write a function


for calculating compound interest and call it

Aim:
To create a function that calculates the compound interest based on the
principal amount, rate of interest, and time period.

Program:
# defining the main function
def main_function():
# asking the user for input
p = float(input("Enter the Principal Amount: "))
r = float(input("Enter the Rate of Interest: "))
n = float(input("Enter the Number of times that interest is compounded
per unit t: "))
t = float(input("Enter the Time Period: "))
# calling the compound_interest() function and storing the value in
new variable
ci = compound_interest(p, r, n, t)
print()
# printing the result
print("Compound Interest (C.I.): %2f" %ci)

# calling the main_function() function


main_function()

GPC/IQAC/FORMAT/22 23 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Output:

Result:
The program correctly calculates the compound interest based on the
given principal, rate, and time.

GPC/IQAC/FORMAT/22 24 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 11
Date:

Write programs to demonstrate use of following types of inheritance:


Single inheritance, Multiple inheritance, Multilevel inheritance
Aim:
To implement and demonstrate single, multiple, and multilevel
inheritance in Python through class hierarchy and method overriding.

Program:
# Base class (Single Inheritance)
class Animal:
def speak(self):
return "Animal makes a sound"

# Derived class
class Dog(Animal):
def speak(self):
return "Woof!"

# Create an instance of the derived class


my_dog = Dog()

# Call the method from the derived class


print(my_dog.speak()) # Output: Woof!

# Base class 1 (Multiple Inheritance)


class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, my name is {self.name}."
# Base class 2
class Employee:
def __init__(self, employee_id):
self.employee_id = employee_id
def get_id(self):
return f"My employee ID is {self.employee_id}."
# Derived class inheriting from both Person and Employee
class Manager(Person, Employee):
def __init__(self, name, employee_id, department):
Person.__init__(self, name) # Initialize Person part
Employee.__init__(self, employee_id) # Initialize Employee part
GPC/IQAC/FORMAT/22 25 | Page
GPC/CIVIL/Python Programming Lab/P2418103

self.department = department
def show_details(self):
return f"{self.greet()} {self.get_id()} I manage the {self.department}
department."

# Create an instance of the derived class


manager = Manager("Alice", "E12345", "Sales")

# Call methods from base classes and derived class


print(manager.greet()) # Output: Hello, my name is Alice.
print(manager.get_id()) # Output: My employee ID is E12345.
print(manager.show_details()) # Output: Hello, my name is Alice. My
employee ID is E12345. I manage the Sales department.

# Base class (Multilevel Inheritance)


class Animal:
def __init__(self, species):
self.species = species
def eat(self):
return f"{self.species} is eating."

# Derived class from Animal


class Mammal(Animal):
def __init__(self, species, fur_color):
super().__init__(species) # Initialize the base class (Animal)
self.fur_color = fur_color
def breathe(self):
return f"{self.species} breathes air."

# Further derived class from Mammal


class Dog(Mammal):
def __init__(self, species, fur_color, name):
super().__init__(species, fur_color) # Initialize the base class
(Mammal)
self.name = name
def bark(self):
return f"{self.name} says Woof!"

# Create an instance of the Dog class


my_dog = Dog("Dog", "Brown", "Buddy")

# Call methods from all levels of the inheritance chain


print(my_dog.eat()) # Output: Dog is eating.
GPC/IQAC/FORMAT/22 26 | Page
GPC/CIVIL/Python Programming Lab/P2418103

print(my_dog.breathe()) # Output: Dog breathes air.


print(my_dog.bark()) # Output: Buddy says Woof!

Output:

Result:
The program successfully demonstrates single, multiple, and multilevel
inheritance in Python, with the derived classes correctly inheriting and
overriding methods from their base classes.

GPC/IQAC/FORMAT/22 27 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Ex. No: 12
Date:

Write Python program to demonstrate file operations.

Aim:
To understand and demonstrate basic file operations in Python, including
creating a file, writing data to it, reading data from it, and appending data to it.

Program:
# 1. Create a new file and write data to it
with open('example_file.txt', 'w') as file:
file.write('This is the initial line of the file.\n')
file.write('Here is another line.\n')

# 2. Read the file to verify the content


with open('example_file.txt', 'r') as file:
print('Contents of the file after writing:')
print(file.read())

# 3. Append more data to the file


with open('example_file.txt', 'a') as file:
file.write('This line is appended to the file.\n')

# 4. Read the file again to verify the appended content


with open('example_file.txt', 'r') as file:
print('Contents of the file after appending:')
print(file.read())

GPC/IQAC/FORMAT/22 28 | Page
GPC/CIVIL/Python Programming Lab/P2418103

Output:
Contents of the file after writing:
This is the initial line of the file.
Here is another line.

Contents of the file after appending:


This is the initial line of the file.
Here is another line.
This line is appended to the file.

Result:
The file operations program creates a file, writes and appends text, and
reads the updated content to confirm the changes.
GPC/IQAC/FORMAT/22 29 | Page

You might also like