VAC - Python Programming Lab - MANUAL
VAC - Python Programming Lab - MANUAL
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
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
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.
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: "))
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.
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.
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")
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.")
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.
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.
9.The main function is called at the end to start the program's execution.
def main():
contact_book = {}
while True:
print("\nContact Book")
print("1. Add Contact")
print("2. Find Contact")
print("3. Quit")
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()
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:
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.
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)
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:
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:
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.
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
attempts = 0
max_attempts = 5
Output:
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.
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.
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 main():
while True:
print("\nCalculator Menu:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Quit")
if choice == "5":
print("Exiting the calculator.")
break
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()
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.
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:
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 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")
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}")
if __name__ == "__main__":
main()
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.
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.
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}")
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()
Result:
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.
6. Displaying Area: Call the calculate_area method on each object and display the
calculated area.
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)
if __name__ == "__main__":
main()
Result:
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.
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.
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
# 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()
Result:
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.
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.
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]
if __name__ == "__main__":
main()
Output:
Result:
Aim:
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("------------------------------")
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.
Aim:
Procedure:
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.
Program:
def main():
# Prepare data
programming_languages = ['Python', 'JavaScript', 'Java',
'C#', 'C++']
popularity = [80, 70, 65, 45, 40] # Example popularity
values (out of 100)
# 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.
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.
Program:
def main():
# Generating sample data
x_values = [1, 2, 3, 4, 5]
y_values = [10, 18, 6, 12, 9]
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()
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()
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”:
urlpatterns = [
path('', views.index, name='index'),
path('greet/', views.greet, name='greet'),
]
Program-2:
<!DOCTYPE html>
Program-3:
In “dynamicform/views.py”:
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.")
Create Django App: Inside the project directory, create a new Django app named
"dynamicform" using the command python manage.py startapp dynamicform.
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.