0% found this document useful (0 votes)
6 views46 pages

VAC - Python Programming Lab - MANUAL

The document is a student reference manual for a Python Programming Lab, detailing various programming exercises and their objectives, such as calculating BMI, managing country-capital pairs, and creating a contact book using dictionaries. Each program includes a description, aim, procedure, and sample code, demonstrating the application of Python concepts like loops, conditionals, and data structures. The manual serves as a guide for students to learn and implement Python programming skills through practical examples.
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)
6 views46 pages

VAC - Python Programming Lab - MANUAL

The document is a student reference manual for a Python Programming Lab, detailing various programming exercises and their objectives, such as calculating BMI, managing country-capital pairs, and creating a contact book using dictionaries. Each program includes a description, aim, procedure, and sample code, demonstrating the application of Python concepts like loops, conditionals, and data structures. The manual serves as a guide for students to learn and implement Python programming skills through practical examples.
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
You are on page 1/ 46

Python Programming Lab

(Student reference Manual)

S. No. Description of Program Page No.

01. Calculate the Body Mass Index (BMI) using Elementary data 02
items (Number and Strings)
02. Find the sum, average, maximum, and minimum values from 04
list of numbers using list
Interactive interface for country-capital pairs with the help of
03. 06
loop and conditional statements using dictionaries

04. Create a simple contact number book using dictionaries 09


05. Store student information and calculate their grade points 12
based on a predefined grading scale using tuples.
06. Number guessing game using conditional branches (if 15
statements) and loops (while loop)
07. Calculator application that performs basic arithmetic 18
operations using functions
08. Banking system simulation using classes and objects 21
09. Library management system using inheritance 25
Finding area of a circle, Rectangle and triangle which are
10. 28
extended multiple subclasses from a base class using
Polymorphism.
Applying numerical computations on an array using
11. 31
mathematical functions from the numpy library.

12. Data manipulation and analysis using pandas library. 34


Grouping and aggregating data from a CSV file using pandas
13. 36
library.
Create a visualization of the popularity of programming
14. 38
languages using the matplotlib library.
Creating various types of plots to visualize data and patterns
15. 40
using matplotlib library.
01. Calculate the Body Mass Index (BMI) using Elementary data items
(Number and Strings)

Aim:
To develop a Python program using elementary data items that calculates the Body
Mass Index (BMI) for a person based on their inputs for name, age, height, and
weight. The program should also provide an interpretation of the BMI value.

Procedure:
1. Ask the user to input their name.
2. Ask the user to input their age.
3. Ask the user to input their height in meters.
4. Ask the user to input their weight in kilograms.
5. Calculate the BMI using the formula: BMI = weight / (height * height).
6. Determine the BMI status based on the calculated BMI value:
BMI < 18.5: "Underweight"
18.5 <= BMI < 24.9: "Normal weight"
25 <= BMI < 29.9: "Overweight"
BMI >= 30: "Obese"
7. Display the calculated BMI value, status, name, and age to the user.

Program:
def main():
# declare variables
name = input("Enter your name: ")
age = int(input("Enter your age: "))
height = float(input("Enter your height in cm: "))
weight = float(input("Enter your weight in kg: "))

# calculate BMI
bmi = weight / (height/100)**2

# print BMI status


if bmi < 18.5:
print(f"{name}, your BMI is {bmi}. You are underweight.")
elif bmi < 25:
print(f"{name}, your BMI is {bmi}. You are healthy.")
elif bmi < 30:
print(f"{name}, your BMI is {bmi}. You are overweight.")
else:
print(f"{name}, your BMI is {bmi}. You are obese.")

Python Programming Lab Department of Computer Applications, TPGASC.


2
if __name__ == "__main__":
main()

Output:

Result:
The user is prompted to input their name, age, height, and weight. The program
then calculates the BMI using the provided values and the BMI formula. Based on
the calculated BMI, the program determines the BMI status and displays the results
along with the user's name and age. This program demonstrated how elementary
data items are used to perform calculations and provide relevant information.

Craft Your Code:


1. Convert temperatures between Celsius and Fahrenheit scales. fahrenheit = (celsius
* 9/5) + 32) and Celsius = ((Fahrenheit – 32) * 5/9)
2. Program that takes a user's name and age as input and then displays a
personalized greeting message using strings

Python Programming Lab Department of Computer Applications, TPGASC.


3
02. Find the sum, average, maximum, and minimum values from list of
numbers using

Aim:
To develop a Python program that accepts a list of numbers from the user and
performs various operations on the list, such as finding the sum, average, maximum,
and minimum values.

Procedure:
1. Ask the user to input the length of the list.
2. Create an empty list to store the numbers.
3. Using a loop, ask the user to input each number and add it to the list.
4. Calculate the sum of all numbers in the list.
5. Calculate the average of the numbers.
6. Find the maximum and minimum values in the list.
7. Display the sum, average, maximum, minimum, and the entire list.

Program:
# Step 1: Ask the user to input the length of the list
length = int(input("Enter the length of the list: "))

# Step 2: Create an empty list


numbers = []

# Step 3: Input each number and add to the list


for i in range(length):
num = float(input(f"Enter number {i+1}: "))
numbers.append(num)

# Step 4: Calculate the sum of the numbers


total_sum = sum(numbers)

# Step 5: Calculate the average


average = total_sum / length

# Step 6: Find the maximum and minimum values


maximum = max(numbers)
minimum = min(numbers)

# Step 7: Display results


print("List of Numbers:", numbers)
print("Sum:", total_sum)

Python Programming Lab Department of Computer Applications, TPGASC.


4
print("Average:", average)
print("Maximum:", maximum)
print("Minimum:", minimum)

Output:

Result:
The user is prompted to input the length of the list and each individual number. The
program then performs calculations such as finding the sum, average, maximum,
and minimum values using the provided list of numbers. Finally, the program
displayed the results along with the entire list.

Craft Your Code:


Sort a list of integers in ascending order and descending order using sort()
method. For descending order use sort(reverse=True)

Python Programming Lab Department of Computer Applications, TPGASC.


5
03. Interactive interface for country-capital pairs with the help of loop and
conditional statements using dictionaries

Aim:

The aim of this program is to create a simple interactive interface using a loop and
conditional statements to manage country-capital pairs. Users can add new country-
capital pairs, delete existing countries, display all country-capital pairs, or quit the
program.

Procedure:
1. Initialization: The program starts by initializing an empty dictionary called
country_capital_dict to store country-capital pairs.

2. User Interaction Loop: The program enters a while loop that displays a menu of
options to the user: adding a country-capital pair, deleting a country, displaying all
country-capital pairs, or quitting the program.

3. Add Country-Capital Pair: If the user chooses to add a country-capital pair, they
are prompted to enter the name of the country and its corresponding capital. The
program then adds this pair to the country_capital_dict dictionary.

4. Delete Country: If the user chooses to delete a country, they are prompted to enter
the name of the country they want to delete. If the country exists in the dictionary, it
is removed. Otherwise, a message is displayed indicating that the country was not
found.

5. Display All Country-Capital Pairs: If the user chooses to display all country-
capital pairs, the program iterates through the country_capital_dict dictionary and
prints each country-capital pair.

6. Quit: If the user chooses to quit, the loop is exited, and the program terminates.

7. Invalid Choice Handling: If the user enters an invalid choice, an appropriate


message is displayed.

Python Programming Lab Department of Computer Applications, TPGASC.


6
Program:

country_capital_dict = {}

while True:
print("\nCountry-Capital Dictionary")
print("1. Add Country-Capital Pair")
print("2. Delete Country")
print("3. Display All Country-Capital Pairs")
print("4. Quit")

choice = input("Select an option: ")

if choice == "1":
country = input("Enter country: ")
capital = input("Enter capital: ")
country_capital_dict[country] = capital
print(f"Added {country} - {capital} to the
dictionary.")
elif choice == "2":
country = input("Enter country to delete: ")
if country in country_capital_dict:
del country_capital_dict[country]
print(f"Deleted {country} from the dictionary.")
else:
print(f"{country} not found in the dictionary.")
elif choice == "3":
print("\nCountry-Capital Pairs:")
for country, capital in country_capital_dict.items():
print(f"{country}: {capital}")
elif choice == "4":
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")

Python Programming Lab Department of Computer Applications, TPGASC.


7
Output:

Result:

When you run the program, it presents a menu-driven interface that allows you to
interactively manage country-capital pairs. The user can add new pairs, delete
countries, display the stored pairs, or quit the program. The pairs are stored in a
dictionary where country names are keys and capital names are values.

Craft Your Code:


Store and display student information using a dictionary for each student with keys
like "name", "age", and "grade".

Python Programming Lab Department of Computer Applications, TPGASC.


8
04. Create a simple contact number book using dictionaries

Aim:
The aim of this program is to create a simple contact book using dictionaries in
Python. Users can add new contacts with names and phone numbers, and also
search for existing contacts by name.

Procedure:
1. The program starts by defining a add_contact function that takes a contact book
(a dictionary), a name, and a phone number as arguments. This function adds the
name and phone number as a key-value pair to the contact book dictionary.

2. Another function called find_contact is defined. It takes the contact book and a
name as arguments. If the given name exists in the contact book, the associated
phone number is printed. If the name is not found, a message indicating that the
name was not found is printed.

3. The main function is defined to serve as the main entry point of the program.
Inside the main function, an empty dictionary called contact_book is created to
store the contacts.

4. The program enters a while loop that displays a menu of options to the user:
adding a contact, finding a contact, or quitting the program.

5. If the user chooses to add a contact, they are prompted to enter a name and a
phone number. The add_contact function is then called to add this information to
the contact book.

6. If the user chooses to find a contact, they are prompted to enter a name. The
find_contact function is then called to search for the name in the contact book
and display the associated phone number.

7. If the user chooses to quit, the program exits the loop and displays a message
before terminating.

8. If the user enters an invalid choice, an appropriate message is displayed.

9.The main function is called at the end to start the program's execution.

Python Programming Lab Department of Computer Applications, TPGASC.


9
Program:
def add_contact(contact_book, name, phone_number):
contact_book[name] = phone_number
print(f"Added {name} to the contact book.")

def find_contact(contact_book, name):


if name in contact_book:
print(f"{name}: {contact_book[name]}")
else:
print(f"{name} not found in the contact book.")

def main():
contact_book = {}

while True:
print("\nContact Book")
print("1. Add Contact")
print("2. Find Contact")
print("3. Quit")

choice = input("Select an option: ")

if choice == "1":
name = input("Enter name: ")
phone_number = input("Enter phone number: ")
add_contact(contact_book, name, phone_number)
elif choice == "2":
name = input("Enter name: ")
find_contact(contact_book, name)
elif choice == "3":
print("Exiting the contact book.")
break
else:
print("Invalid choice. Please select a valid
option.")

if __name__ == "__main__":
main()

Python Programming Lab Department of Computer Applications, TPGASC.


10
Output:

Python Programming Lab Department of Computer Applications, TPGASC.


11
Result:
The program provides a simple user interface where you can add contacts and find
their phone numbers. As you add contacts, their names and phone numbers are
stored in the contact_book dictionary. When you search for a contact, the program
looks up the contact's name in the dictionary and displays the associated phone
number if it exists.

Overall, this program demonstrates how to use dictionaries to build a basic contact
book application in Python, allowing you to manage and retrieve contact
information efficiently.

05. Store student information and calculate their grade points based on a
predefined grading scale using tuples.

Aim:

The aim of this program is to create a Python program using tuples to store student
information, calculate their grade points based on a predefined grading scale, and
display the student records along with their grade points.

Procedure:

1. Initialization: The program starts by defining an empty list called student_records


to store student information. Each student's information will be stored as a tuple
containing their name, roll number, marks, and calculated grade point.

2. Grade Point Calculation: The program defines a function called


calculate_grade_point. This function takes a student's marks as input and calculates
their grade point based on a predefined grading scale. The calculated grade point is
returned.

3. User Input Loop: The program enters a loop where users can input student details.
For each student, the program prompts for their name, roll number, and marks.

4. Calculate Grade Points: The calculate_grade_point function is called with the


entered marks to calculate the grade point for each student.

Python Programming Lab Department of Computer Applications, TPGASC.


12
5. Create Student Tuple: The student's name, roll number, marks, and calculated
grade point are packaged into a tuple and appended to the student_records list.

6. Display Student Records: After gathering information for all students, the
program displays the student records along with their calculated grade points. The
records are formatted to include student names, roll numbers, marks, and grade
points.

Program:

def calculate_grade_point(marks):
if marks >= 90:
return 4.0
elif marks >= 80:
return 3.7
elif marks >= 70:
return 3.3
elif marks >= 60:
return 3.0
elif marks >= 50:
return 2.7
elif marks >= 40:
return 2.3
else:
return 0.0

student_records = []

while True:
print("\nEnter Student Details:")
name = input("Name: ")
roll_number = input("Roll Number: ")
marks = float(input("Marks: ")) # Assuming marks are
entered as a floating-point number

grade_point = calculate_grade_point(marks)

student_tuple = (name, roll_number, marks, grade_point)


student_records.append(student_tuple)

choice = input("Do you want to enter details for another


student? (yes/no): ")
if choice.lower() != "yes":

Python Programming Lab Department of Computer Applications, TPGASC.


13
break

print("\nStudent Records:")
for student in student_records:
name, roll_number, marks, grade_point = student
print(f"Name: {name}, Roll Number: {roll_number}, Marks:
{marks}, Grade Point: {grade_point:.2f}")

Note:

The "f" in the string formatting expression f"Name: {name}, Roll Number:
{roll_number}, Marks: {marks}, Grade Point: {grade_point:.2f}"
stands for an f-string or formatted string literal. F-strings are a feature introduced in
Python 3.6 that allow you to embed expressions inside string literals, making string
formatting more concise and readable.

Output:

Result:

This program provides a user-friendly interface to input student details and


calculate their grade points. The program calculates the grade points based on a
predefined grading scale and displays the student records along with their
calculated grade points. And demonstrates how tuples can be used to store related
pieces of information, and how functions can be employed to perform calculations

Python Programming Lab Department of Computer Applications, TPGASC.


14
based on certain criteria. It showcases a practical application of data storage,
processing, and display in a cohesive program.

Craft Your Code:


Store and display book information using tuples for each book with elements like
title, author, and publication year.

06. Number guessing game using conditional branches (if statements) and loops
(while loop)

Aim:

The aim of this program is to create a number guessing game using conditional
branches (if statements) and loops (while loop). The program generates a random
target number between 1 and 100 and asks the user to guess the number. The
program provides feedback based on the user's guesses and informs them about the
number of attempts taken to guess the correct number.

Procedure:

1. Initialization: The program imports the random module to generate random


numbers and initializes variables like target_number, attempts, and max_attempts.

2. Introduction: The program welcomes the player to the Number Guessing Game
and explains that it's thinking of a number between 1 and 100.

3. User Input Loop: The program enters a while loop that repeatedly prompts the
player to enter their guess.

4. Player Guess: The player enters their guess, and the program increments the
attempts counter to keep track of the number of guesses.

5. Conditional Branches (if, elif, else): The program uses conditional statements to
compare the player's guess with the target_number:

• If the guess is lower than target_number, the program informs the player to
try a higher number.
• If the guess is higher than target_number, the program informs the player to
try a lower number.

Python Programming Lab Department of Computer Applications, TPGASC.


15
• If the guess matches target_number, the program congratulates the player for
guessing the correct number, displays the number of attempts, and terminates
the loop.

6. Loop Termination: If the player uses all their attempts without guessing the
correct number, the program exits the while loop and informs the player that the
game is over and reveals the correct target_number.

Program:

import random

# Generate a random number between 1 and 100


target_number = random.randint(1, 100)

print("Welcome to the Number Guessing Game!")


print("I'm thinking of a number between 1 and 100.")

attempts = 0
max_attempts = 5

while attempts < max_attempts:


guess = int(input("\nEnter your guess: "))
attempts += 1

if guess < target_number:


print("Too low! Try a higher number.")
elif guess > target_number:
print("Too high! Try a lower number.")
else:
print(f"Congratulations! You guessed the number
{target_number} in {attempts} attempts.")
break
else:
print(f"\nGame over! The number was {target_number}. You
used all {max_attempts} attempts.")

Output:

Python Programming Lab Department of Computer Applications, TPGASC.


16
Result:

The program provides an interactive number guessing game experience. The player
is informed about the game rules and asked to guess a randomly generated target
number. As the player makes guesses, the program provides feedback about
whether the guess is too low or too high. If the player guesses the correct number
within the allowed number of attempts, they are congratulated and informed about
the number of attempts taken. If the player uses all their attempts without guessing
the correct number, they are informed about the end of the game and the correct
target number. And showcases how conditional statements and loops can be used
together to create an interactive game that engages the player in a guessing
challenge.

Craft Your Code:


Create a pattern printing program with conditional branches and loops. Ask the
number of rows as input.
*
**
***
****
*****

Python Programming Lab Department of Computer Applications, TPGASC.


17
07. Calculator application that performs basic arithmetic operations using
functions

Aim:

The aim of this program is to create a simple calculator application that performs
basic arithmetic operations (addition, subtraction, multiplication, division) on two
numbers using functions for modularity and reusability.

Procedure:

1. Function Definitions: Define four functions for each of the arithmetic operations:
add, subtract, multiply, and divide. Each function should take two arguments
(operands) and return the result of the respective operation.

2. User Input: Prompt the user to enter two numbers and select an arithmetic
operation from a menu of options.

3. Function Invocation: Based on the user's chosen operation, call the appropriate
function and pass the input numbers as arguments.

4. Display Result: Display the calculated result to the user.

5. Repeat or Quit: Ask the user if they want to perform another calculation. If yes,
repeat the process from step 2. If no, end the program.

Program:

def add(x, y):


return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


if y != 0:
return x / y
else:

Python Programming Lab Department of Computer Applications, TPGASC.


18
return "Cannot divide by zero"

def main():
while True:
print("\nCalculator Menu:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Quit")

choice = input("Select an operation (1/2/3/4/5): ")

if choice == "5":
print("Exiting the calculator.")
break

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))

if choice == "1":
result = add(num1, num2)
elif choice == "2":
result = subtract(num1, num2)
elif choice == "3":
result = multiply(num1, num2)
elif choice == "4":
result = divide(num1, num2)
else:
print("Invalid choice. Please select a valid
option.")
continue

print(f"Result: {result}")

if __name__ == "__main__":
main()

Python Programming Lab Department of Computer Applications, TPGASC.


19
Output:

Result:

The program will provide a simple calculator menu where users can input two
numbers and select an arithmetic operation. The program will then perform the
chosen operation using the corresponding function and display the result. It
demonstrates how functions can be used to encapsulate code for specific tasks,
promoting modularity and reusability within the program.

Craft Your Code:


Determine if a given year is a leap year or not by using functions.
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) then Boolean value is True

Python Programming Lab Department of Computer Applications, TPGASC.


20
08. Banking system simulation using classes and objects

Aim:

The aim of this program is to create a simple banking system simulation using
classes and objects. The program will allow users to create bank accounts, deposit
and withdraw funds, and view account balances.

Procedure:

1. Class Definition: Define a BankAccount class with methods to create an account,


deposit funds, withdraw funds, and view the account balance. Each bank account
will have attributes such as an account number, account holder's name, and current
balance.

2. Account Creation: Prompt the user to enter their name and an initial deposit to
create a bank account. The program should generate a unique account number for
each account.

3. Deposit Funds: Ask the user to provide an account number and the amount they
want to deposit. Use the deposit method of the corresponding BankAccount object to
add the funds to the account.

4. Withdraw Funds: Similarly, ask the user for an account number and the amount
they want to withdraw. Use the withdraw method of the BankAccount object to
deduct the funds if sufficient balance is available.

5. View Account Balance: Prompt the user for an account number and use the
get_balance method to display the account's current balance.

Program:

class BankAccount:
account_counter = 1 # A class variable to keep track of
account numbers

def __init__(self, name, initial_balance):


self.account_number = BankAccount.account_counter
self.account_holder = name

Python Programming Lab Department of Computer Applications, TPGASC.


21
self.balance = initial_balance
BankAccount.account_counter += 1

def deposit(self, amount):


if amount > 0:
self.balance += amount
return True
return False

def withdraw(self, amount):


if 0 < amount <= self.balance:
self.balance -= amount
return True
return False

def get_balance(self):
return self.balance

def main():
accounts = []

while True:
print("\nBanking System Menu:")
print("1. Create Account")
print("2. Deposit Funds")
print("3. Withdraw Funds")
print("4. View Account Balance")
print("5. Quit")

choice = input("Select an option (1/2/3/4/5): ")

if choice == "5":
print("Exiting the banking system.")
break

if choice == "1":
name = input("Enter your name: ")
initial_balance = float(input("Enter initial
deposit amount: "))
account = BankAccount(name, initial_balance)
accounts.append(account)
print(f"Account created with number
{account.account_number}")

Python Programming Lab Department of Computer Applications, TPGASC.


22
elif choice == "2":
account_number = int(input("Enter account number:
"))
amount = float(input("Enter amount to deposit: "))
for account in accounts:
if account.account_number == account_number:
if account.deposit(amount):
print("Deposit successful.")
else:
print("Invalid amount for deposit.")

# Implement similar code for options 3 and 4

elif choice == "3":


account_number = int(input("Enter account number:
"))
amount = float(input("Enter amount to withdraw:
"))
for account in accounts:
if account.account_number == account_number:
if account.withdraw(amount):
print("Withdrawal successful.")
else:
print("Insufficient balance or invalid
amount for withdrawal.")

elif choice == "4":


account_number = int(input("Enter account number:
"))
for account in accounts:
if account.account_number == account_number:
balance = account.get_balance()
print(f"Account balance for account
{account_number}: {balance:.2f}")

if __name__ == "__main__":
main()

Python Programming Lab Department of Computer Applications, TPGASC.


23
Output:

Result:

The program simulates a basic banking system where users can create accounts,
deposit and withdraw funds, and view account balances. The use of classes and
objects encapsulates the behaviour and attributes of bank accounts, promoting a
structured and organized approach to the program.

Craft Your Code:


Create a simple student information system using classes and objects.
o Define a class called Student with attributes like name, age, and grades.
o Define methods to calculate the average grade and display student
information.
o Create instances of the Student class to represent individual students.

Python Programming Lab Department of Computer Applications, TPGASC.


24
09. Library management system using inheritance

Aim:

The aim of this program is to create a simple library management system using
inheritance. The program will involve creating a base class for a general item, and
then creating specific subclasses for books and magazines, each inheriting properties
and methods from the base class.

Procedure:

1. Base Class Definition: Create a base class called LibraryItem with attributes like
title, author (or publisher for magazines), and a method to display item information.

2. Subclass Definition (Books): Create a subclass called Book that inherits from
LibraryItem. Add attributes specific to books like ISBN and number of pages.
Override the display method to include book-specific information.

3. Subclass Definition (Magazines): Create another subclass called Magazine that


also inherits from LibraryItem. Add attributes specific to magazines like issue
number and publication date. Override the display method for magazine-specific
information.

4. Creating Objects: Create instances of Book and Magazine classes by providing


appropriate values for their attributes.

5. Displaying Information: Call the display methods of the created objects to see their
details.

Program:

class LibraryItem:
def __init__(self, title, author_publisher):
self.title = title
self.author_publisher = author_publisher

def display(self):
print(f"Title: {self.title}")

Python Programming Lab Department of Computer Applications, TPGASC.


25
print(f"Author/Publisher: {self.author_publisher}")

class Book(LibraryItem):
def __init__(self, title, author, isbn, num_pages):
super().__init__(title, author)
self.isbn = isbn
self.num_pages = num_pages

def display(self):
super().display()
print(f"ISBN: {self.isbn}")
print(f"Number of Pages: {self.num_pages}")

class Magazine(LibraryItem):
def __init__(self, title, publisher, issue_number,
publication_date):
super().__init__(title, publisher)
self.issue_number = issue_number
self.publication_date = publication_date

def display(self):
super().display()
print(f"Issue Number: {self.issue_number}")
print(f"Publication Date: {self.publication_date}")

def main():
book = Book("The Great Gatsby", "F. Scott Fitzgerald",
"978-0-684-80146-7", 180)
magazine = Magazine("National Geographic", "National
Geographic Society", "August 2023", "08/01/2023")

print("\nBook Details:")
book.display()

print("\nMagazine Details:")
magazine.display()

if __name__ == "__main__":
main()

Python Programming Lab Department of Computer Applications, TPGASC.


26
Output:

Result:

The program demonstrates inheritance by creating a base class LibraryItem and


subclasses Book and Magazine that inherit from it. The base class provides a method
to display general item information, while the subclasses override this method to
include specific information about books and magazines. It will create instances of
Book and Magazine classes, display their details using the overridden display
methods, and demonstrate the concept of inheritance in object-oriented
programming.

Craft Your Code:


Create a hierarchy of classes representing vehicles using inheritance.
o Define a base class Vehicle with attributes like make, model, and methods like
start_engine().
o Define subclasses Car and Motorcycle that inherit from Vehicle.
o Add attributes and methods specific to each subclass, such as num_doors for
Car and has_sidecar for Motorcycle.

Python Programming Lab Department of Computer Applications, TPGASC.


27
10. Finding area of a circle, Rectangle and triangle which are extended multiple
subclasses from a base class using Polymorphism.

Aim:

The aim of this program is to create a simple example of polymorphism using a base
class and multiple subclasses. The program will demonstrate how different
subclasses can implement the same method in different ways, allowing for flexibility
and extensibility in the code.

Procedure:

1. Base Class Definition: Create a base class called Shape with a method
calculate_area that doesn't have an implementation.

2. Subclass Definition (Circle): Create a subclass called Circle that inherits from
Shape. Implement the calculate_area method to calculate and return the area of a
circle using its radius.

3. Subclass Definition (Rectangle): Create another subclass called Rectangle that also
inherits from Shape. Implement the calculate_area method to calculate and return
the area of a rectangle using its length and width.

4. Subclass Definition (Triangle): Create a third subclass called Triangle that inherits
from Shape. Implement the calculate_area method to calculate and return the area of
a triangle using its base and height.

5. Creating Objects: Create instances of each subclass, providing appropriate values


for their attributes.

6. Displaying Area: Call the calculate_area method on each object and display the
calculated area.

Python Programming Lab Department of Computer Applications, TPGASC.


28
Program:

class Shape:
def calculate_area(self):
pass

class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def calculate_area(self):
return 3.14 * self.radius ** 2

class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width

def calculate_area(self):
return self.length * self.width

class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height

def calculate_area(self):
return 0.5 * self.base * self.height

def main():
circle = Circle(5)
rectangle = Rectangle(4, 6)
triangle = Triangle(3, 8)

shapes = [circle, rectangle, triangle]

for shape in shapes:


area = shape.calculate_area()
print(f"Area of {type(shape).__name__}: {area:.2f}")

if __name__ == "__main__":
main()

Python Programming Lab Department of Computer Applications, TPGASC.


29
Output:

Result:

The program demonstrates polymorphism by creating a base class Shape and


subclasses Circle, Rectangle, and Triangle. Each subclass implements the
calculate_area method differently based on its specific shape formula.

It will create instances of different shapes, call the calculate_area method on each
object, and display the calculated area. This showcases how polymorphism allows
different subclasses to have their own implementations of a common method,
enabling dynamic behaviour based on the specific object type.

Craft Your Code:


Use polymorphism to process payments from different payment methods.
o Define a base class PaymentMethod with a method
process_payment(amount) that returns a payment confirmation message.
o Define subclasses CreditCard and PayPal that inherit from
PaymentMethod and provide their own implementations of
process_payment().
o Create instances of different payment methods and call the
process_payment() method on each.

Python Programming Lab Department of Computer Applications, TPGASC.


30
11. Applying numerical computations on an array using mathematical functions
from the numpy library.

Aim:

The aim of this program is to demonstrate the usage of the numpy library in Python
for performing numerical computations efficiently. The program will involve
creating arrays, performing basic operations on them, and applying mathematical
functions from the numpy library.

Procedure:

1. Import Numpy: Import the numpy library at the beginning of the program to use
its functionalities.

2. Creating Arrays: Create one-dimensional and two-dimensional arrays using


numpy. Populate them with numerical data.

3. Basic Operations: Perform basic array operations such as element-wise addition,


subtraction, multiplication, and division.

4. Mathematical Functions: Apply mathematical functions provided by numpy on


the arrays, such as square root and exponential.

5. Array Manipulation: Reshape arrays, access specific elements, and find maximum
and minimum values.

Program:

import numpy as np

def main():
# Creating arrays
one_dim_array = np.array([1, 2, 3, 4, 5])
two_dim_array = np.array([[1, 2, 3], [4, 5, 6]])

# Basic operations
addition = one_dim_array + 10
subtraction = two_dim_array - 2

Python Programming Lab Department of Computer Applications, TPGASC.


31
multiplication = one_dim_array * 3
division = two_dim_array / 2

# Mathematical functions
square_root = np.sqrt(one_dim_array)
exponential = np.exp(one_dim_array)

# Array manipulation
reshaped_array = two_dim_array.reshape(3, 2)
element_at_index = one_dim_array[2]
max_value = np.max(two_dim_array)
min_value = np.min(two_dim_array)

# Display results
print("One-dimensional Array:", one_dim_array)
print("Two-dimensional Array:", two_dim_array)
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Square Root:", square_root)
print("Exponential:", exponential)
print("Reshaped Array:", reshaped_array)
print("Element at Index 2:", element_at_index)
print("Max Value:", max_value)
print("Min Value:", min_value)

if __name__ == "__main__":
main()

Python Programming Lab Department of Computer Applications, TPGASC.


32
Output:

Result:

The program showcases various functionalities of the numpy library, such as


creating arrays, performing basic operations, applying mathematical functions, and
manipulating arrays.

It will display the arrays and the results of the operations and functions applied to
them and demonstrates how numpy can be used to efficiently handle numerical
computations and operations on arrays.

Craft Your Code:


Matrix multiplication (3 X 3) and statistical calculations like mean, median, and
standard deviation using NumPy functions.

Python Programming Lab Department of Computer Applications, TPGASC.


33
12. Data manipulation and analysis using pandas library.

Aim:

The aim of this program is to demonstrate the usage of the pandas library in Python
for data manipulation and analysis. The program will involve creating and
manipulating data frames, performing basic operations, and displaying information
from the data.

Procedure:

1. Import Pandas: Import the pandas library at the beginning of the program to use
its functionalities.

2. Creating Data Frames: Create a data frame using pandas to represent tabular data.
Populate it with sample data.

3. Basic Operations: Perform basic data manipulation operations such as selecting


columns, filtering rows, and calculating summary statistics.

4. Display Information: Display information from the data frame, including column
names, a summary of statistics, and selected rows.

Program:

import pandas as pd

def main():
# Creating a data frame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David',
'Eva'],
'Age': [25, 30, 22, 28, 24],
'Salary': [50000, 60000, 45000, 55000, 52000]}

df = pd.DataFrame(data)

# Basic operations
salary_mean = df['Salary'].mean()
youngest_person = df[df['Age'] == df['Age'].min()]
high_earners = df[df['Salary'] > 55000]

Python Programming Lab Department of Computer Applications, TPGASC.


34
# Displaying information
print("Data Frame:")
print(df)
print("\nAverage Salary:", salary_mean)
print("\nYoungest Person:")
print(youngest_person)
print("\nHigh Earners:")
print(high_earners)

if __name__ == "__main__":
main()

Output:

Result:

The program demonstrates various functionalities of the pandas library, such as


creating data frames, performing basic operations, and displaying information from
the data. It will calculate the average salary, show the youngest person's
information, and display the data of high earners. This showcases how pandas can
be used to efficiently manipulate and analyze tabular data.

Python Programming Lab Department of Computer Applications, TPGASC.


35
13. Grouping and aggregating data from a CSV file using pandas library

Aim:

Use pandas to group and aggregate data from a CSV file.

Procedure:

1. Import the pandas library: This step imports the pandas library, which is widely
used for data manipulation and analysis in Python.

2. Read data from a CSV file: The program uses the pd.read_csv() function to read
data from a CSV file named "data.csv". The CSV file contains sample data in a
tabular format with columns "Name," "Age," and "Salary".

3. Group data by age and calculate aggregation: The program uses the groupby()
function to group the data based on the "Age" column. After grouping, the agg()
function is applied to perform aggregation operations on the grouped data. In this
case, the program calculates the sum and mean of the "Salary" column and also
counts the number of occurrences (i.e., the number of names) for each age group.

4. Display the aggregated results: Finally, the program displays the aggregated
results using print(). The aggregated data shows the sum and mean of salaries, as
well as the count of names for each unique age group.

Program:
import pandas as pd

def main():
print("PANDAS GROUPING AND AGGREGATION")
print("------------------------------")

# Read data from CSV file


data = pd.read_csv("data.csv")

# Group data by age and calculate sum, mean, and count


grouped_data = data.groupby('Age').agg({'Salary': ['sum',
'mean'], 'Name': 'count'})

print("Grouped and Aggregated Data:")


print(grouped_data)

Python Programming Lab Department of Computer Applications, TPGASC.


36
# Call the main function to start the program
if __name__ == "__main__":
main()

Output:

Result:

The program demonstrates the process of grouping and aggregating data using the
pandas library. The output displays the aggregated results in a tabular format,
providing insights into how salaries vary across different age groups.

Note:
1. Open a text editor (like Notepad on Windows or TextEdit on macOS).
2. Enter the following content into the text editor:
Name,Age,Salary
Alice,28,60000
Bob,32,75000
Charlie,25,50000
David,22,45000
Eva,29,62000
3. Save the file as "data.csv" in the same directory where your Python script is
located. This content represents the data in comma-separated values (CSV) format.
Each line represents a record with columns for Name, Age, and Salary.

Python Programming Lab Department of Computer Applications, TPGASC.


37
14. Create a visualization of the popularity of programming languages using the
matplotlib library.

Aim:

The aim of this program is to create a visualization of the popularity of


programming languages using the matplotlib library in Python. The program will
involve creating a bar plot to show the relative popularity of different programming
languages based on an interesting dataset.

Procedure:

1. Import Matplotlib: Import the matplotlib.pyplot module to use its plotting


functionalities.

2. Prepare Data: Create a dictionary or lists containing programming languages and


their popularity values.

3. Create Bar Plot: Use the bar function from matplotlib to create a bar plot using the
data.

4. Customize Plot: Add labels, title, and other visual elements to the plot to make it
more informative.

5. Display Plot: Use the show function to display the plot.

Program:

import matplotlib.pyplot as plt

def main():
# Prepare data
programming_languages = ['Python', 'JavaScript', 'Java',
'C#', 'C++']
popularity = [80, 70, 65, 45, 40] # Example popularity
values (out of 100)

# Create bar plot


plt.figure(figsize=(10, 6))
plt.bar(programming_languages, popularity,
color='skyblue')
plt.xlabel('Programming Languages')

Python Programming Lab Department of Computer Applications, TPGASC.


38
plt.ylabel('Popularity (%)')
plt.title('Popularity of Programming Languages')
plt.ylim(0, 100) # Set y-axis limits to ensure the
percentage scale
plt.grid(axis='y')

# Display plot
plt.show()

if __name__ == "__main__":
main()

Output:

Result:

The program creates a bar plot that visualizes the popularity of different
programming languages based on the provided popularity values. It will display a
bar plot showing the relative popularity of programming languages. The x-axis will
represent the programming languages, the y-axis will represent the popularity
percentage, and each bar will represent a programming language's popularity. This
example showcases how matplotlib can be used to create visually appealing and
informative data visualizations.

Python Programming Lab Department of Computer Applications, TPGASC.


39
15. Creating various types of plots to visualize data and patterns using matplotlib
library.

Aim:

The aim of this program is to demonstrate the usage of the matplotlib library in
Python for data visualization. The program will involve creating various types of
plots to visualize data and patterns.

Procedure:

1. Import Matplotlib: Import the matplotlib library at the beginning of the program
to use its functionalities.

2. Generating Data: Create sample data that you want to visualize using plots. For
example, you can create lists of x and y values for plotting.

3. Creating Plots: Use matplotlib functions to create different types of plots, such as
line plots, bar plots, and scatter plots.

4. Customizing Plots: Customize the appearance of the plots by adding labels, titles,
legends, and other visual elements.

5. Displaying Plots: Display the generated plots using matplotlib functions.

Program:

import matplotlib.pyplot as plt

def main():
# Generating sample data
x_values = [1, 2, 3, 4, 5]
y_values = [10, 18, 6, 12, 9]

# Creating a line plot


plt.figure(figsize=(8, 6))
plt.plot(x_values, y_values, marker='o', linestyle='-',
color='b', label='Data Points')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot Example')

Python Programming Lab Department of Computer Applications, TPGASC.


40
plt.legend()
plt.grid(True)
plt.show()

# Creating a bar plot


categories = ['Category A', 'Category B', 'Category C',
'Category D', 'Category E']
values = [30, 45, 15, 60, 25]

plt.figure(figsize=(8, 6))
plt.bar(categories, values, color='g')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Plot Example')
plt.grid(axis='y')
plt.show()

# Creating a scatter plot


x_values_scatter = [3, 5, 7, 9, 11]
y_values_scatter = [12, 8, 18, 5, 9]

plt.figure(figsize=(8, 6))
plt.scatter(x_values_scatter, y_values_scatter, color='r',
marker='^')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')
plt.grid()
plt.show()

if __name__ == "__main__":
main()

Python Programming Lab Department of Computer Applications, TPGASC.


41
Output:

Python Programming Lab Department of Computer Applications, TPGASC.


42
Result:

The program demonstrates various functionalities of the matplotlib library by


creating line plots, bar plots, and scatter plots. The different types of plots generated
from the sample data. This showcases how matplotlib can be used to visualize data
and patterns, aiding in data exploration and communication.

Python Programming Lab Department of Computer Applications, TPGASC.


43
16. Creating a dynamic and interactive web page to respond a server with a
personalized greeting based on the input using Django.

Aim:

The aim of this program is to create a dynamic and interactive web page using
Django, a powerful web framework for Python. The program will involve creating a
simple web form where users can input their name and age, and the server will
respond with a personalized greeting based on the input.

Procedure:

1. Install Django: Install Django if you haven't already using pip install Django.

2. Create Django Project: Create a new Django project using the command django-
admin startproject projectname.

3. Create Django App: Inside the project directory, create a new Django app using
the command python manage.py startapp appname.

4. Define URL Routes: In the app's urls.py, define URL routes for the views.

5. Create HTML Form: Create an HTML template with a form for input inside the
app's templates directory.

6. Create Views: Define views in the app's views.py. Create a view for the form and
another view to process the form data.

Program-1:

In “dynamicform/urls.py”:

from django.urls import path


from . import views

urlpatterns = [
path('', views.index, name='index'),
path('greet/', views.greet, name='greet'),
]

Program-2:

Create HTML Form:


Create a file named form.html inside dynamicform/templates directory:

<!DOCTYPE html>

Python Programming Lab Department of Computer Applications, TPGASC.


44
<html>
<head>
<title>Dynamic Form</title>
</head>
<body>
<h1>Dynamic Form</h1>
<form action="{% url 'greet' %}" method="post">
{% csrf_token %}
<label for="name">Name:</label>
<input type="text" id="name" name="name"
required><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age"
required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Program-3:

In “dynamicform/views.py”:

from django.shortcuts import render


from django.http import HttpResponse

def index(request):
return render(request, 'form.html')

def greet(request):
if request.method == 'POST':
name = request.POST['name']
age = int(request.POST['age'])
greeting = f"Hello, {name}! You are {age} years old."
return HttpResponse(greeting)
return HttpResponse("Form submission error.")

Python Programming Lab Department of Computer Applications, TPGASC.


45
Note:

Install Django: Install Django using pip install Django.

Create Django Project: Create a new Django project named "DynamicFormProject"


using the command django-admin startproject DynamicFormProject.

Create Django App: Inside the project directory, create a new Django app named
"dynamicform" using the command python manage.py startapp dynamicform.

Define URL Routes:


a) In dynamicform/urls.py
b) Create a file named form.html inside dynamicform/templates directory
c) Create Views: In dynamicform/views.py

To run the program, navigate to the project directory containing manage.py and run
the command python manage.py runserver. Open your web browser and visit
http://localhost:8000 to access the dynamic and interactive web form. You can input
your name and age in the form, submit it, and see the personalized greeting
displayed on the page.

Output:

Result:

This program demonstrates how to create dynamic and interactive web pages with
forms using Django. It highlights Django's URL routing, views, and template
rendering capabilities to create an interactive web experience.

Disclaimer:

This Python Programming Lab Manual has been prepared based on the syllabus
prescribed with various resources available online. Every step is taken to avoid
mistakes as far as possible in this material, human errors are possible.

Python Programming Lab Department of Computer Applications, TPGASC.


46

You might also like