0% found this document useful (0 votes)
18 views30 pages

Python Rec

10 Exercise Problem for the Python Programming

Uploaded by

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

Python Rec

10 Exercise Problem for the Python Programming

Uploaded by

yoganathan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

CONTENTS

PAGE
S.NO DATE TITLE OF THE PROGRAM SIGNATURE
NO

PROGRAM USING ELEMENTARY DATA


1.
ITEMS, LIST, DICTIONARIES AND TUPLES

PROGRAM USING CONDITIONAL


2.
BRANCHES AND LOOPS

3. PROGRAM USING FUNCTIONS

4. PROGRAM USING CLASSES AND OBJECTS

5. PROGRAM USING INHERITANCE

6. PROGRAM USING POLYMORPHISM

7. PROGRAM USING NUMPY

8. PROGRAM USING PANDAS

9. PROGRAM USING MATPLOTLIB

CREATING DYNAMIC AND INTERACTIVE


10.
WEB PAGES USING FORMS
SOURCE CODE:
contacts = { }
def add_contact( name, phone_number, email):
if name in contacts:
print(f"Contact {name} already exixts.")
else:
contacts[name]={
'phone_number':phone_number,
'email':email}
print(f"Contact {name} added.")
def view_contacts():
if not contacts:
print("No contacts Available.")
return
for name, details in contacts.items():
print(f"Name: {name}")
print(f"Phone Number: {details['phone_number']}")
print(f"Email: {details['email']}")
print("-"*20)
def delete_contact(name):
if name in contacts:
del contacts[name]
print(f"Contact {name} deleted.")
else:
print(f"Contact {name} not Found.")
def search_contact(name):
if name in contacts:
details=contacts[name]
print(f"Name: {name}")
print(f"Phone Number: {details['phone_number']}")
print(f"Email: {details['email']}")
else:
print(f"Contact {name} not Found.")
def main():
while True:
print("\n Contact Management System")
print("1. Add Contact")
print("2. View Contact")
print("3. Delete Contact")
print("4. Search Contact")
print("5. Exit")
choice= input("Enter Your Choice(1-5):")
if choice=='1':
name= input("Enter Contact Name: ")
phone_number=input("Enter Phone Number: ")
email=input("Enter email Address: ")
add_contact(name, phone_number, email)
elif choice=='2':
view_contacts()
elif choice=='3':
name=input("Enter Contact Name: ")
delete_contact(name)
elif choice=='4':
name=input("Enter Contact Name: ")
search_contact(name)
elif choice=='5':
print('Exiting')
break
else:
print("Invalid Choice. Please try again")
if __name__=="__main__":
main()

OUTPUT:
SOURCE CODE:
employees = {}
def add_employee(employee_id, name, hourly_rate):
employees[employee_id] = {
'name': name,
'hourly_rate': hourly_rate,
'hours_worked': 0,
'bonuses': 0,
'deductions': 0}
def update_hours_worked(employee_id, hours):
if employee_id in employees:
employees[employee_id]['hours_worked'] += hours
else:
return 'Employee Not Found'
def add_bonus(employee_id, bonus):
if employee_id in employees:
employees[employee_id]['bonuses'] += bonus
else:
return 'Employee Not Found'
def add_deduction(employee_id, deduction):
if employee_id in employees:
employees[employee_id]['deductions'] += deduction
else:
return 'Employee Not Found'
def calculate_paybill(employee_id):
employee = employees.get(employee_id)
if employee:
basic_pay = employee['hours_worked'] * employee['hourly_rate']
total_pay = basic_pay + employee['bonuses'] -
employee['deductions']
if total_pay < 0:
total_pay = 0
return {
'name': employee['name'],
'hours_worked': employee['hours_worked'],
'basic_pay': basic_pay,
'bonuses': employee['bonuses'],
'deductions': employee['deductions'],
'total_pay': total_pay}
else:
return 'Employee Not Found'
def print_pay_bill(paybill):
if isinstance(paybill, str):
print(paybill)
else:
print(f"\nPay Bill for {paybill['name']}:")
print(f" Hours Worked: {paybill['hours_worked']}")
print(f" Basic Pay: ${paybill['basic_pay']:.2f}")
print(f" Bonuses: ${paybill['bonuses']:.2f}")
print(f" Deductions: ${paybill['deductions']:.2f}")
print(f" Total Pay: ${paybill['total_pay']:.2f}")
def get_user_input():
num_employees = int(input("Enter the number of employees: "))
for _ in range(num_employees):
employee_id = int(input('Enter Employee Id: '))
name = input('Enter Employee Name: ')
hourly_rate = float(input('Enter Hourly Rate: '))
add_employee(employee_id, name, hourly_rate)
hours_worked = float(input('Enter Hours Worked: '))
update_hours_worked(employee_id, hours_worked)
bonus = float(input("Enter Bonuses: "))
add_bonus(employee_id, bonus)
deduction = float(input('Enter Deductions: '))
add_deduction(employee_id, deduction)
paybill = calculate_paybill(employee_id)
print_pay_bill(paybill)
get_user_input()

OUTPUT:
SOURCE CODE:
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 "Error! Division by zero."
return x / y
def modulus(x, y):
return x % y
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
while True:
choice = input("Enter choice (1/2/3/4/5): ")
if choice in ('1', '2', '3', '4', '5'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input! Please enter a number.")
continue
if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
elif choice == '5':
print(f"{num1} % {num2} = {modulus(num1, num2)}")
else:
print("Invalid choice! Please select a valid operation.")
next_calculation = input("Do you want to perform another
calculation? (yes/no): ")
if next_calculation.lower() != 'yes':
break
if __name__ == "__main__":
calculator()
OUTPUT:
SOURCE CODE:
class BankAccount:
def __init__(self, account_number, account_holder, balance=0):
self.account_number = account_number
self.account_holder = account_holder
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited {amount}. New balance: {self.balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrew {amount}. New balance: {self.balance}")
else:
print("Insufficient balance or invalid amount.")
def display_balance(self):
print(f"Account Holder: {self.account_holder}")
print(f"Account Number: {self.account_number}")
print(f"Current Balance: {self.balance}")
if __name__ == "__main__":
account_number = input("Enter account number: ")
account_holder = input("Enter account holder name: ")
initial_balance = float(input("Enter initial balance: "))
account = BankAccount(account_number, account_holder,
initial_balance)
while True:
print("\nChoose an option:")
print("1. Deposit")
print("2. Withdraw")
print("3. Display Balance")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
amount = float(input("Enter amount to deposit: "))
account.deposit(amount)
elif choice == '2':
amount = float(input("Enter amount to withdraw: "))
account.withdraw(amount)
elif choice == '3':
account.display_balance()
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
OUTPUT:
SOURCE CODE:
class LibraryItem:
def __init__(self, title, author, publication_year):
self.title=title
self.author=author
self.publication_year=publication_year
def display_info(self):
print(f"Title:{self.title}")
print(f"Author:{self.author}")
print(f"Publication Year:{self.publication_year}")
class Book(LibraryItem):
def __init__(self, title, author, publication_year, isbn, genre):
super().__init__(title, author, publication_year)
self.isbn=isbn
self.genre=genre
def display_info(self):
super().display_info()
print(f"ISBN:{self.isbn}")
print(f"Genre:{self.genre}")
class Magazine(LibraryItem):
def __init__(self, title, author, publication_year, issue_number):
super().__init__(title, author, publication_year)
self.issue_number=issue_number
def display_info(self):
super().display_info()
print(f"Issue Number: {self.issue_number}")
book1= Book("The Great Gatsby", "F.Scott Fitzgerald", 1925, "978-
0743273565", "Fiction")
magazine1= Magazine("National geographic", "Various Authors", 2023,
42)
print("Book Information:")
book1.display_info()
print("\n Magazine Information:")
magazine1.display_info()

OUTPUT:
SOURCE CODE:
class Animal:
def sound(self):
raise NotImplementedError("Subclass must implemented abstract
method")
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
class Bird(Animal):
def sound(self):
return "Chirp!"
def make_animal_sound(animal):
print(animal.sound())
dog=Dog()
cat=Cat()
bird=Bird()
make_animal_sound(dog)
make_animal_sound(cat)
make_animal_sound(bird)
OUTPUT:
SOURCE CODE:
import numpy as np
matrix_A = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
matrix_B = np.array([[9,8,7],
[6,5,4],
[3,2,1]])
matrix_addition = np.add(matrix_A, matrix_B)
matrix_multiplication = np.multiply(matrix_A, matrix_B)
matrix_dot_product = np.dot(matrix_A, matrix_B)
print("\nMatrix Dot Product (A dot B):")
print(matrix_dot_product)
matrix_transpose = np.transpose(matrix_A)
print("Matrix A:")
print(matrix_A)
print("Matrix B")
print(matrix_B)
print("\nMatrix addition (A+B):")
print(matrix_addition)
print("\nMatrix Element-wise Multiplication(A * B):")
print(matrix_multiplication)
OUTPUT:
SOURCE CODE:
import pandas as pd
data_series = pd.Series([10, 20, 30, 40, 50], index=['Ananya', 'Rohan',
'Vikram', 'Sneha', 'Aditi'])
print("Original Series:")
print(data_series)
print("\nElement for index 'Vikram':")
print(data_series['Vikram'])
series_add = data_series + 5
print("\nSeries after adding 5 to each element:")
print(series_add)
filtered_series = data_series[data_series > 20]
print("\nElements greater than 20 in the series:")
print(filtered_series)
data = {
'Name': ['Ananya', 'Rohan', 'Vikram', 'Sneha', 'Aditi'],
'Age': [24, 27, 22, 32, 29],
'City': ['Mumbai', 'Delhi', 'Bangalore', 'Hyderabad', 'Chennai'],
'Salary': [50000, 54000, 58000, 60000, 62000]}
dataframe = pd.DataFrame(data)
print("\nOriginal Data Frame:")
print(dataframe)
print("\nAccess 'Name' Column:")
print(dataframe['Name'])
print("\nAccess row with index 2 (Vikram):")
print(dataframe.iloc[2])
filtered_dataframe = dataframe[dataframe['Age'] > 25]
print("\nFilter rows where Age > 25:")
print(filtered_dataframe)
dataframe['Bonus'] = dataframe['Salary'] * 0.10
print("\nDataFrame after Adding 'Bonus' column:")
print(dataframe)
average_salary = dataframe['Salary'].mean()
print(f"\nAverage salary: {average_salary}")
grouped_data = dataframe.groupby('City')['Salary'].mean()
print("\nAverage Salary by City:")
print(grouped_data)

OUTPUT:
SOURCE CODE:
import numpy as np
import matplotlib.pyplot as plt
days=np.arange(1,31)
temperature=np.random.uniform(low=20, high=40, size=30)
average_temp=np.mean(temperature)
max_temp=np.max(temperature)
min_temp=np.min(temperature)
cold_days=np.sum(temperature<25)
moderate_days=np.sum((temperature>=25)&(temperature<=35))
hot_days=np.sum(temperature>35)
fig, axs=plt.subplots(1, 3, figsize=(18, 5))
axs[0].plot(days, temperature, label="Daily Temperature", marker='o',
color='b')
axs[0].axhline(average_temp, color='r', linestyle='--', label=f'Average
Temp:{average_temp:2f}C')
axs[0].set_title('Line Chart: Daily Temperature')
axs[0].set_xlabel('Day of the Month')
axs[0].set_ylabel('Temperature(C)')
axs[0].legend()
axs[1].bar(days, temperature, color='orange')
axs[1].set_title('Bar Chart: Daily Temperature')
axs[1].set_xlabel('Day of the Month')
axs[1].set_ylabel('tempoerature(C)')
labels=['Cold Days(<25C)', 'Moderate Days(25-35C)','Hot Days(>35C)']
sizes=[cold_days, moderate_days, hot_days]
colors=['blue','green','red']
axs[2].pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%',
startangle=140)
axs[2].set_title('Pie Chart: Temperature Distribution')
plt.tight_layout()
plt.show()

OUTPUT:
SOURCE CODE:

1. Create a New Django Project:


django-admin startproject bmi_calculator
cd bmi_calculator

2. Create a New Django App:


python manage.py startapp bmi

bmi_calculator/urls.py:
from django.contrib import admin
from django.urls import path , include
urlpatterns = [
path("admin/", admin.site.urls),
path('bmi/', include('bmi.urls')),]
bmi_calculator/settings.py:
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"bmi"]
bmi/urls.py:
from django.urls import path
from .import views
urlpatterns = [
path('', views.bmi_calculator, name='bmi_calculator'),]
bmi/views.py:
from django.shortcuts import render
from .forms import BMIForm
def bmi_calculator(request):
bmi = None
category = ''
if request.method == 'POST':
form = BMIForm(request.POST)
if form.is_valid():
weight = form.cleaned_data['weight']
height = form.cleaned_data['height']
height = height / 100
bmi = weight / (height ** 2)
if bmi < 18.5:
category = 'Under Weight'
elif 18.5 <= bmi <= 24.9:
category = 'Normal Weight'
elif 25 <= bmi <= 29.9:
category = 'Over Weight'
else:
category = 'Obesity'
else:
form = BMIForm()
return render(request, 'bmi/bmi_calculator.html', {'form': form,
'bmi': bmi, 'category': category})

bmi/forms.py:
from django import forms

class BMIForm(forms.Form):
weight = forms.FloatField(label="weight (k)", min_value = 0)
height = forms.FloatField(label="height (m)", min_value = 0)
bmi/templates/bmi/bmi_calculator.html:
<hmtl>
<head>
<title> BMI Calculator </title>
</head>
<body>
<h1> BMI Calculator </h1>
<form method = "POST">
{% csrf_token %}
{{form.as_p}}
<button type="submit"> Calculate </button>
</form>

{% if bmi %}
<h2> Your BMI: {{ bmi|floatformat:2}} </h2>
<h3> Category: {{ category}} </h3>
{% endif %}
</body>
</html>

3. Run the Development Server:


python manage.py runserver

OUTPUT:

You might also like