0% found this document useful (0 votes)
3 views25 pages

Python Programing Lab Manual

The Python Programming Manual for MLDE258C at Srinivas Institute of Technology outlines the course objectives, program outcomes, and specific skills students will acquire, including data analysis and GUI application development. It includes a comprehensive list of experiments that cover various Python programming tasks, such as mathematical computations, file handling, and database operations. The manual emphasizes the importance of innovative teaching and skill development to enhance employability in the field of Electronics and Communication Engineering.

Uploaded by

kshithib
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views25 pages

Python Programing Lab Manual

The Python Programming Manual for MLDE258C at Srinivas Institute of Technology outlines the course objectives, program outcomes, and specific skills students will acquire, including data analysis and GUI application development. It includes a comprehensive list of experiments that cover various Python programming tasks, such as mathematical computations, file handling, and database operations. The manual emphasizes the importance of innovative teaching and skill development to enhance employability in the field of Electronics and Communication Engineering.

Uploaded by

kshithib
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SRINIVAS INSTITUTE OF TECHNOLOGY, VALACHIL,

MANGALURU- 574143
(Affiliated to VTU, Belgaum, Approved by AICTE)

PYTHON PROGRAMMING (MLDE258C) MANUAL

PREPARED BY

Mrs. Flavita Janice Pinto


Assistant Professor
DEPARTMENT OF ECE

DEPARTMENT OF ELECTRONICS AND COMMUNICATION


ENGINEERING
SRINIVAS INSTITUTE OF TECHNOLOGY,
MANGALURU - 574143

1
Python Programming (MLDE258C) Manual

VISION
To be a centre of excellence in Electronics and Communication
Engineering with quality education and research, responsive to the needs
of industry and society.

MISSION

 To achieve academic excellence through innovative teaching-learning


practice.
 To inculcate the spirit of innovation, creativity and research.
 To enhance employability through skill development and industry-
institute interaction.
 To develop professionals with ethical values and social responsibilities.

Program Specific Outcomes (PSOs)

PSO1: Hardware and hardware-software co-design: Ability to


identify, design, simulate, analyze and develop Electronic circuits and
systems, using modern engineering tools and programming languages.

PSO2: Domain specific skills: Ability to work in the field of Embedded


System, VLSI, Image Processing, Machine learning and Network
Engineering.

2
Python Programming (MLDE258C) Manual

Program outcomes (POs)


Graduates will be able to:
PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.
PO2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
PO10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.

3
Python Programming (MLDE258C) Manual

VTU SYLLABUS
Python Programming
Course Code MLDE258C CIE Marks 50
Teaching Hours/Week (L:T:P) 0:0:2 SEE Marks 50
Credits -01 Exam Hours:3 Total Marks 100
Course objectives:
To provide skills for modelling and simulation of communication systems & networks on MatLab platform. To
provide skills for writing MatLab programs and use communication and signal processing toolboxes.
To enable the students to implement and validate the algorithms studied in Communication.
To enable the students to implement and validate the algorithms studied in Communication.
Sl. NO Experiments
1. Write a Python program that calculates the sum of the first n terms of the following mathematical
series:

2. Write a Python program that reads a file and calculates the number of characters, words, and lines in
it.
3. Write a Python program to compute various matrix and vector operations such as dot product, inner
product, outer product, and matrix exponentiation.
4. a) Write a Python program that uses Pandas' built-in visualization tools to create the following
plots:
 Bar plots
 Histograms
 Line plots
 Scatter plots
b) Write a program to demonstrate the use of the groupby() method in Pandas.
c) Write a program that shows how to merge, join, and concatenate dataframes in Pandas.
d) Write a Python program to create dataframes from CSV and Excel files.
5. Write a python program to check the validity of a password given by the user. The password should
satisfy the following criteria:
a) Contain at least 1 letter between a and z
b) Contain at least 1 number between 0 and 9
c) Contain at least 1 letter between A and Z
d) Contain at least 1 character from $, #, @
e) Minimum length of password: 6
f) Maximum length of password: 12
6. Write a Python program that performs basic database operations (create, insert, delete, update) using
MySQL and its corresponding Python adapter
7. Write a Python program that accepts a space-separated sequence of words as input and
outputs the words in a hyphen-separated sequence after sorting them alphabetically.
8. Write a Python program that demonstrates data indexing, selection, and filtering using Pandas.
9. a) Write a Python GUI application that simulates traffic lights with appropriate colors and text
for "Stop", "Wait", and "Go" signals.
b) Write a python program for simple GUI calculator using Tk.
10. Create a Python class named Person with attributes for name, age, weight (in kg), and height (in
feet). The class should have a method get_bmi_result() that calculates the BMI and returns whether
the person is "underweight",
4
Python Programming (MLDE258C) Manual

"healthy", or "obese"

11. Write a Python program to demonstrate various types of inheritance.


12. Write a Python program that creates abstract classes and implements abstract methods.
Course outcomes (Course Skill Set):
At the end of the course the student will be able to:

 Students will be able to design and implement Python programs that solve complex problems, including mathematical series, file
handling, matrix operations, and more.
 Students will be capable of effectively managing and analyzing datasets using Python libraries like Pandas and NumPy,
and visualizing the data through bar plots, histograms, line plots, and scatter plots.
 Students will demonstrate the ability to connect Python programs to MySQL databases, perform CRUD (Create, Read, Update,
Delete) operations, and manage database interactions proficiently.
 Students will be able to apply object-oriented programming concepts like inheritance and abstraction, and develop interactive
GUI applications using Tkinter, enhancing the user experience in software solutions
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%. The

5
Python Programming (MLDE258C) Manual

CONTENTS
Sl. No List of Experiments Page
No.
1. Write a Python program that calculates the sum of the first n terms of the following 8
mathematical series:

2. Write a Python program that reads a file and calculates the number of characters, 9
words, and lines in it.
3. Write a Python program to compute various matrix and vector operations such as 10
dot product, inner product, outer product, and matrix exponentiation.

4. b) Write a Python program that uses Pandas' built-in visualization tools to create the 11
following plots:
 Bar plots
 Histograms
 Line plots
 Scatter plots
e) Write a program to demonstrate the use of the groupby() method in Pandas.
f) Write a program that shows how to merge, join, and concatenate dataframes in
Pandas.
g) Write a Python program to create dataframes from CSV and Excel files.
5. Write a python program to check the validity of a password given by the user. The 14
password should satisfy the following criteria:
g) Contain at least 1 letter between a and z
h) Contain at least 1 number between 0 and 9
i) Contain at least 1 letter between A and Z
j) Contain at least 1 character from $, #, @
k) Minimum length of password: 6
l) Maximum length of password: 12
6. Write a Python program that performs basic database operations (create, insert, 15
delete, update) using MySQL and its
corresponding Python adapter
7. Write a Python program that accepts a space-separated sequence of words as 17
input and outputs the words in a hyphen-separated sequence after sorting
them alphabetically.
8. Write a Python program that demonstrates data indexing, selection, and filtering 18
using Pandas.

6
Python Programming (MLDE258C) Manual

c) Write a Python GUI application that simulates traffic lights with appropriate 19
9. colors and text for "Stop", "Wait", and "Go" signals.
d) Write a python program for simple GUI calculator using Tk.
Create a Python class named Person with attributes for name, age, weight (in kg),
10. and height (in feet). The class should have a method get_bmi_result() that calculates 20
the BMI and returns whether the person is "underweight",
"healthy", or "obese"
Write a Python program to demonstrate various types of inheritance.
11. 21
Write a Python program that creates abstract classes and implements abstract
12. methods. 23

7
Python Programming (MLDE258C) Manual

Expt. No. 1 WRITE A PYTHON PROGRAM THAT CALCULATES THE SUM OF


THE FIRST N TERMS OF THE FOLLOWING MATHEMATICAL
SERIES

AIM
To write a Python program that calculates the sum of the first n terms of the following
mathematical series

PROGRAM

import math

def cosine_series_sum(x, n):


result = 1 # First term is 1
for i in range(1, n + 1):
power = 2 * i
term = (x ** power) / [Link](power)
result += (-1) ** i * term # Alternate signs: -term, +term, ...
return result

# Example usage
x=2
n=3
print("Sum of series:", cosine_series_sum(x, n))

RESULT

Sum of series: -0.4222222222222223

8
Python Programming (MLDE258C) Manual

Expt. No. 2 WRITE A PYTHON PROGRAM THAT READS A FILE AND


CALCULATES THE NUMBER OF CHARACTERS, WORDS, AND
LINES IN IT

AIM
To Write a Python program that reads a file and calculates the number of characters,
words, and lines in it.

PROCEDURE
• Save a file with 3 lines and some characters in notepad on the desktop having path
C:/Users/EC/Desktop/[Link]

PROGRAM

def count_file_stats(file_path):
try:
with open(file_path, 'r') as file:
lines = [Link]()
num_lines = len(lines)
num_words = sum(len([Link]()) for line in lines)
num_chars = sum(len(line) for line in lines)
print(f"File: {file_path}")
print(f"Total lines: {num_lines}")
print(f"Total words: {num_words}")
print(f"Total characters: {num_chars}")
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
file_path = "C:/Users/EC/Desktop/[Link]"
count_file_stats(file_path)

RESULT

9
Python Programming (MLDE258C) Manual

Expt. No. 3 WRITE A PYTHON PROGRAM TO COMPUTE VARIOUS MATRIX


AND VECTOR OPERATIONS SUCH AS DOT PRODUCT, INNER
PRODUCT, OUTER PRODUCT, AND MATRIX EXPONENTIATION

AIM

To Write a Python program to compute various matrix and vector operations such as dot
product, inner product, outer product, and matrix exponentiation.

PROGRAM

import numpy as np

a = [Link]([1, 2])
b = [Link]([3, 4])

print("Dot product:", [Link](a, b))


print("Outer product:\n", [Link](a, b))
print("Inner product:", [Link](a, b))

m = [Link]([[1, 2], [3, 4]])


print("Matrix exponentiation:\n", [Link].matrix_power(m, 2))

RESULT

Dot product: 11
Outer product:
[[3 4]
[6 8]]
Inner product: 11
Matrix exponentiation:
[[ 7 10]
[15 22]]

10
Python Programming (MLDE258C) Manual

Expt. No. 4 A) WRITE A PYTHON PROGRAM THAT USES PANDAS' BUILT-IN


VISUALIZATION TOOLS TO CREATE THE FOLLOWING PLOTS: • BAR
PLOTS • HISTOGRAMS • LINE PLOTS • SCATTER PLOTS B) WRITE A
PROGRAM TO DEMONSTRATE THE USE OF THE GROUPBY() METHOD IN
PANDAS. C) WRITE A PROGRAM THAT SHOWS HOW TO MERGE, JOIN,
AND CONCATENATE DATAFRAMES IN PANDAS. D) WRITE A PYTHON
PROGRAM TO CREATE DATAFRAMES FROM CSV AND EXCEL FILES

AIM

To a) Write a Python program that uses Pandas' built-in visualization tools to create the
following plots: • Bar plots • Histograms • Line plots • Scatter plots b) Write a program to
demonstrate the use of the groupby() method in Pandas. c) Write a program that shows how to
merge, join, and concatenate dataframes in Pandas. d) Write a Python program to create
dataframes from CSV and Excel files

PROGRAM

import pandas as pd
import [Link] as plt
# Sample DataFrame
data = {
"Name": ["Alice", "Bob", "Charlie", "David"],
"Age": [25, 30, 35, 40],
"Salary": [50000, 60000, 70000, 80000]
}
df = [Link](data)

# a) Visualization
[Link](kind="bar", x="Name", y="Salary", title="Bar Plot")
[Link]()
df["Age"].plot(kind="hist", title="Histogram")
[Link]()
[Link](kind="line", x="Name", y="Age", title="Line Plot")
[Link]()
[Link](kind="scatter", x="Age", y="Salary", title="Scatter Plot")
[Link]()

# b) GroupBy
grouped = [Link]("Age")["Salary"].mean()
print(grouped)

# c) Merge, Join, Concatenate


df1 = [Link]({"ID": [1, 2], "Name": ["Alice", "Bob"]})
df2 = [Link]({"ID": [1, 2], "Dept": ["HR", "IT"]})
11
Python Programming (MLDE258C) Manual

merged = [Link](df1, df2, on="ID")


print(merged)
joined = df1.set_index("ID").join(df2.set_index("ID"))
print(joined)
concat_df = [Link]([df1, df2], axis=1)
print(concat_df)

# d) Create DataFrame from CSV/Excel


# df_csv = pd.read_csv("[Link]")
# df_excel = pd.read_excel("[Link]")

RESULT

12
Python Programming (MLDE258C) Manual

13
Python Programming (MLDE258C) Manual

Expt. No. 5 WRITE A PYTHON PROGRAM TO CHECK THE VALIDITY OF A


PASSWORD GIVEN BY THE USER

AIM

Write a python program to check the validity of a password given by the user. The password
should satisfy the following criteria:
a) Contain at least 1 letter between a and z
b) Contain at least 1 number between 0 and 9
c) Contain at least 1 letter between A and Z
d) Contain at least 1 character from $, #, @
e) Minimum length of password: 6
f) Maximum length of password: 12

PROGRAM
import re

def validate_password(pwd):
if (6 <= len(pwd) <= 12 and
[Link]("[a-z]", pwd) and
[Link]("[A-Z]", pwd) and
[Link]("[0-9]", pwd) and
[Link]("[$#@]", pwd)):
return "Valid Password"
return "Invalid Password"

pwd = input("Enter password: ")


print(validate_password(pwd))

RESULT

14
Python Programming (MLDE258C) Manual

Expt. No. 6 WRITE A PYTHON PROGRAM THAT PERFORMS BASIC


DATABASE OPERATIONS (CREATE, INSERT, DELETE, UPDATE)
USING MYSQL AND ITS CORRESPONDING PYTHON ADAPTER
AIM
To write a Python program that performs basic database operations (create, insert, delete,
update) using MySQL and its corresponding Python adapter

PROGRAM

import [Link]

# Connect to MySQL
conn = [Link](
host="localhost",
user="root",
password="your_password", # change to your real password
database="testdb"
)
cursor = [Link]()

# Helper function to show table contents


def show_students(step):
print(f"\n--- {step} ---")
[Link]("SELECT * FROM students")
rows = [Link]()
if rows:
for row in rows:
print(row)
else:
print("No records found.")

# Create table
[Link]("""
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT
)
""")
[Link]()
show_students("After table creation (should be empty)")

# Insert data
[Link]("INSERT INTO students (name, age) VALUES (%s, %s)", ("Alice", 22))
[Link]()
show_students("After inserting Alice")
15
Python Programming (MLDE258C) Manual

# Update data
[Link]("UPDATE students SET age = %s WHERE name = %s", (23, "Alice"))
[Link]()
show_students("After updating Alice's age")

# Delete data
[Link]("DELETE FROM students WHERE name = %s", ("Alice",))
[Link]()
show_students("After deleting Alice")

# Close connection
[Link]()
[Link]()

RESULT

--- After table creation (should be empty) ---


No records found.

--- After inserting Alice ---


(1, 'Alice', 22)

--- After updating Alice's age ---


(1, 'Alice', 23)

--- After deleting Alice ---


No records found.

16
Python Programming (MLDE258C) Manual

Expt. No. 7 WRITE A PYTHON PROGRAM THAT ACCEPTS A SPACE-


SEPARATED SEQUENCE OF WORDS AS INPUT AND OUTPUTS THE
WORDS IN A HYPHEN-SEPARATED SEQUENCE AFTER SORTING
THEM ALPHABETICALLY.
AIM
To write a Python program that accepts a space-separated sequence of words as input and
outputs the words in a hyphen-separated sequence after sorting them alphabetically.

PROGRAM

words = input("Enter words: ").split()


[Link]()
print("-".join(words))

RESULT

17
Python Programming (MLDE258C) Manual

Expt. No. 8 WRITE A PYTHON PROGRAM THAT DEMONSTRATES DATA


INDEXING, SELECTION, AND FILTERING USING PANDAS

AIM
To Write a Python program that demonstrates data indexing, selection, and filtering using
Pandas

PROGRAM

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}


df = [Link](data)

print("Single column:\n", df['Name'])


print("Filter Age > 28:\n", df[df['Age'] > 28])

RESULT

18
Python Programming (MLDE258C) Manual

Expt. No. 9 WRITE A PYTHON GUI APPLICATION THAT SIMULATES TRAFFIC


LIGHTS WITH APPROPRIATE COLORS AND TEXT FOR "STOP",
"WAIT", AND "GO" SIGNALS.
AIM
To write a Python GUI application that simulates traffic lights with appropriate colors and
text for "Stop", "Wait", and "Go" signals.

PROGRAM

import tkinter as tk

def show_signal(color):
[Link](text=color, fg=color)

root = [Link]()
lbl = [Link](root, text="Signal", font=('Arial', 24))
[Link]()
[Link](root, text="Stop", command=lambda: show_signal("Red")).pack()
[Link](root, text="Wait", command=lambda: show_signal("Yellow")).pack()
[Link](root, text="Go", command=lambda: show_signal("Green")).pack()
[Link]()

RESULT

19
Python Programming (MLDE258C) Manual

Expt. No. 10 CREATE A PYTHON CLASS NAMED PERSON WITH ATTRIBUTES


FOR NAME, AGE, WEIGHT (IN KG), AND HEIGHT (IN FEET). THE
CLASS SHOULD HAVE A METHOD GET_BMI_RESULT() THAT
CALCULATES THE BMI AND RETURNS WHETHER THE PERSON IS
"UNDERWEIGHT", "HEALTHY", OR "OBESE"

AIM
To Create a Python class named Person with attributes for name, age, weight (in kg), and height
(in feet). The class should have a method get_bmi_result() that calculates the BMI and returns
whether the person is "underweight", "healthy", or "obese".

PROGRAM
class Person:
def __init__(self,name, age, weight, height):
[Link] = name
[Link] = age
[Link] = weight
[Link] = height

def get_bmi_result(self):
height_m = [Link] * 0.3048
bmi = [Link] / (height_m ** 2)
if bmi < 18.5:
return "Underweight"
elif 18.5 <= bmi < 25:
return "Healthy"
else:
return "Obese"

p = Person("Alice", 30, 70, 5.5)


print(p.get_bmi_result())

RESULT

20
Python Programming (MLDE258C) Manual

Expt. No. 11 WRITE A PYTHON PROGRAM TO DEMONSTRATE VARIOUS TYPES


OF INHERITANCE

AIM
To write a Python program to demonstrate various types of inheritance.

PROGRAM
# Single Inheritance
class Animal:
def speak(self):
print("Animal makes a sound")

class Dog(Animal):
def speak(self):
print("Dog barks")

# Multiple Inheritance
class Father:
def skills(self):
print("Can drive")

class Mother:
def skills(self):
print("Can cook")

class Child(Father, Mother):


def skills(self):
[Link](self)
[Link](self)
print("Can play football")

# Multilevel Inheritance
class GrandParent:
def property(self):
print("Owns a farm")

class Parent(GrandParent):
def property(self):
print("Owns a car")

class Son(Parent):
def property(self):
print("Owns a bike")

# Hierarchical Inheritance
class Vehicle:
21
Python Programming (MLDE258C) Manual

def type(self):
print("This is a vehicle")

class Car(Vehicle):
def type(self):
print("This is a car")

class Bike(Vehicle):
def type(self):
print("This is a bike")

# Demonstration
print("Single Inheritance:")
d = Dog()
[Link]()

print("\nMultiple Inheritance:")
c = Child()
[Link]()

print("\nMultilevel Inheritance:")
s = Son()
[Link]()

print("\nHierarchical Inheritance:")
car = Car()
bike = Bike()
[Link]()
[Link]()

RESULT

Single Inheritance:
Dog barks

Multiple Inheritance:
Can drive
Can cook
Can play football

Multilevel Inheritance:
Owns a bike

Hierarchical Inheritance:
This is a car
This is a bike

22
Python Programming (MLDE258C) Manual

Expt. No. 12 WRITE A PYTHON PROGRAM THAT CREATES ABSTRACT


CLASSES AND IMPLEMENTS ABSTRACT METHODS

AIM
To write a Python program that creates abstract classes and implements abstract methods.

PROGRAM
from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

@abstractmethod
def perimeter(self):
pass

class Rectangle(Shape):
def __init__(self, width, height):
[Link] = width
[Link] = height

def area(self):
return [Link] * [Link]

def perimeter(self):
return 2 * ([Link] + [Link])

class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return 3.1416 * [Link] ** 2

def perimeter(self):
return 2 * 3.1416 * [Link]

# Demonstration
rect = Rectangle(4, 5)
circle = Circle(3)

print("Rectangle area:", [Link]())


print("Rectangle perimeter:", [Link]())
print("Circle area:", [Link]())
23
Python Programming (MLDE258C) Manual

print("Circle perimeter:", [Link]())

RESULT

24
Python Programming (MLDE258C) Manual

Vision & Mission of the Institute


Vision
To be a premier institute of professional education and research,
responsive to the needs of industry and society.

Mission
To achieve academic excellence through innovative teaching- learning
practice, by providing conducive research environment, industry-institute
interaction and skill development, leading to professionals with ethical
values and social responsibilities.

25

You might also like