PPFD - Practicals
PPFD - Practicals
Laboratory
Practical - 1
1. Aim - A program that converts temperature from fahrenheit to celsius
and vice-versa.
Source Code:
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9 / 5) + 32
return fahrenheit
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5 / 9
return celsius
print("Temperature Converter")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
choice = input("Enter your choice (1 or 2): ")
if choice == '1':
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}°C is equal to {fahrenheit:.2f}°F")
elif choice == '2':
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = fahrenheit_to_celsius(fahrenheit)
print(f"{fahrenheit}°F is equal to {celsius:.2f}°C")
else:
print("Invalid choice. Please select 1 or 2.")
Output:
try:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
except ValueError:
print("Invalid input. Please enter numeric values.")
Output:
import random
if length < 5:
print("Password length must be at least 5.")
else:
characters = '1234567890'
for char in range(65,127):
characters += chr(char)
password = ''.join(random.choices(characters, k=length))
print(f"Your random password is: {password}")
Output:
try:
numbers = input("Enter a list of numbers separated by spaces: ")
num_list = [float(num) for num in numbers.split()]
if not num_list:
print("The list is empty. Please enter some numbers.")
else:
average = sum(num_list) / len(num_list)
print(f"The average of the numbers is: {average:.2f}")
except ValueError:
print("Invalid input. Please enter only numbers separated by spaces.")
Output:
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
try:
year = int(input("Enter a year to check: "))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
except ValueError:
print("Invalid input. Please enter a valid year.")
Output:
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
try:
number = int(input("Enter a non-negative integer: "))
if number < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(number)
print(f"The factorial of {number} is: {result}")
except ValueError:
print("Invalid input. Please enter a non-negative integer.")
Output:
def is_palindrome(string):
nospace_string = string.replace(" ", "").lower()
return nospace_string == "".join(reversed(nospace_string))
if is_palindrome(string):
print(f"'{string}' is a palindrome.")
else:
print(f"'{string}' is not a palindrome.")
Output:
try:
numbers = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))
order = input("Enter the sort order (asc/desc): ").lower()
sorted_numbers = sort_numbers(numbers, order)
print(f"Sorted numbers ({order}): {sorted_numbers}")
except ValueError:
print("Invalid input. Please enter valid numbers separated by spaces.")
Output:
def multiplication_table(number):
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
try:
number = int(input("Enter a number : "))
print(f"Multiplication table of {number}:")
multiplication_table(number)
except ValueError:
print("Invalid input. Please enter a valid number.")
Output:
10. Aim - A program that converts a given number from one base to
another.
Source Code:
try:
number = input("Enter the number: ")
from_base = int(input("Enter the base of the number: "))
to_base = int(input("Enter the base to convert to: "))
if from_base < 2 or to_base < 2:
print("Bases must be at least 2.")
else:
converted_number = convert_base(number, from_base, to_base)
print(
f"{number} from base {from_base} to base {to_base} is: {converted_number}"
)
except ValueError:
print("Invalid input. Please enter valid numbers and bases.")
Output:
Set - 2
Program - 1
Aim - A program that models a bank account, with classes for the account,
the customer, and the bank.
Source Code:
class Bank:
def __init__(self, name):
self.name = name
self.customers = []
self.accounts = []
class Customer:
def __init__(self, name, customer_id):
self.name = name
self.customer_id = customer_id
class Account:
def __init__(self, account_number, customer, balance=0.0):
self.account_number = account_number
self.customer = customer
self.balance = balance
def get_balance(self):
return self.balance
bank = Bank("SBI")
customer1 = Customer("Aatish", 1001)
bank.add_customer(customer1)
account1.deposit(25000)
account1.withdraw(15000)
print(f"Final Balance: {account1.get_balance()}")
Output:
Program - 2
Aim - A program that simulates a school management system, with classes
for the students, the teachers, and the courses.
Source Code:
class School:
def __init__(self, name):
self.name = name
self.students = []
self.teachers = []
self.courses = []
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self.courses = []
class Teacher:
def __init__(self, name, teacher_id):
self.name = name
self.teacher_id = teacher_id
self.courses = []
class Course:
def __init__(self, name, course_id, teacher):
self.name = name
self.course_id = course_id
self.teacher = teacher
self.students = []
school = School("PIET")
teacher1 = Teacher("Arunesh Singh", 101)
student1 = Student("Aatish", 107)
student1.enroll(course1)
course1.add_student(student1)
Output:
Program - 3
Aim - A program that reads a text file and counts the number of words in
it.
Source Code:
def count_words_in_file(filename):
try:
with open(filename, 'r') as file:
text = file.read()
words = text.split()
return len(words)
except FileNotFoundError:
print("File not found. Please provide a valid filename.")
return None
filename = "cwords.py"
word_count = count_words_in_file(filename)
if word_count is not None:
print(f"The file '{filename}' contains {word_count} words.")
Output:
Program - 4
Aim - A program that reads a csv file and calculates the average of the
values in a specific column.
Source Code:
import csv
def calculate_average(csv_file, column_name):
total = 0
count = 0
if count == 0:
print("No valid entries found.")
return None
Output:
Program - 5
Aim - A program that reads an excel file and prints the data in a tabular
form.
Source Code:
import pandas as pd
def read_excel_file(file_path):
try:
data = pd.read_excel(file_path)
return data
except Exception as e:
print(f"Error reading the Excel file: {e}")
return None
def print_data_in_table(data):
if data is not None:
print(data.to_string(index=False))
file_path = 'data.xlsx'
data = read_excel_file(file_path)
print_data_in_table(data)
Output:
Set - 3
Program - 1
Aim - A program that creates a simple web server and serves a static
HTML page.
Source Code:
from flask import Flask, render_template
@app.route("/")
def serve_html():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/sakura.css/css/sakura.css" type="text/css">
<title>Static Web Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>This is a simple static page by Aatish.</p>
</body>
</html>
Output:
Program - 2
Aim - A program that creates a web application that allows users to
register and login.
Source Code:
app = Flask(__name__)
app.secret_key = "supersecretkey"
def create_database():
conn = sqlite3.connect('db/db.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL);''')
conn.commit()
conn.close()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login', methods=['GET','POST'])
def login():
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
try:
conn = sqlite3.connect('db/db.db')
c = conn.cursor()
c.execute("SELECT * FROM users WHERE email=?", (email,))
user = c.fetchone()
except sqlite3.Error as e:
flash(f'An error occurred: {e}', 'danger')
finally:
conn.close()
return render_template('login.html')
@app.route('/register', methods=['GET','POST'])
def register():
if request.method == 'POST':
name = request.form.get('name')
email = request.form.get('email')
password = request.form.get('password')
try:
conn = sqlite3.connect('db/db.db')
c = conn.cursor()
c.execute("INSERT INTO USERS (name, email, password) VALUES (?, ?, ?)",
(name, email, password))
conn.commit()
flash('Registration successful!', 'success')
except sqlite3.Error as e:
flash(f'An error occurred: {e}', 'danger')
finally:
conn.close()
return redirect(url_for('login'))
return render_template('register.html')
if __name__ == '__main__':
create_database()
app.run(debug=True)
templates/register.html
{% extends "base.html" %} {% block content %}
<h1>Register</h1>
<form method="POST">
<label for="name">Name</label>
<input type="text" id="name" name="name" required />
<label for="email">Email</label>
<input type="email" id="email" name="email" required />
<label for="password">Password</label>
<input type="password" id="password" name="password" required />
<button type="submit">Register</button>
</form>
{% endblock %}
templates/login.html
{% extends "base.html" %} {% block content %}
<h1>Log In</h1>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
<form method="POST">
<label for="email">Email</label>
<input type="email" id="email" name="email" required />
<label for="password">Password</label>
<input type="password" id="password" name="password" required />
<button type="submit">Log In</button>
</form>
{% endblock %}
templates/index.html
{% extends "base.html" %} {% block content %}
<h1>Welcome</h1>
{% with messages = get_flashed_messages() %} {% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %} {% endwith %}
<a href="/login"><button>Login</button></a>
<a href="/register"><button>Register</button></a>
{% endblock %}
templates/base.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://unpkg.com/sakura.css/css/sakura.css" type="text/css">
</head>
<body>
<main class="container">{% block content %} {% endblock %}</main>
</body>
</html>
Output:
Program - 3
Aim - A program that creates a web application that allows users to upload
and download files.
Source Code:
import os
from flask import Flask, request, render_template, send_from_directory, redirect, url_for
app = Flask(__name__)
UPLOAD_FOLDER = "uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
@app.route("/")
def home():
files = os.listdir(UPLOAD_FOLDER)
return render_template("index.html", files=files)
@app.route("/upload", methods=["POST"])
def upload_file():
if "file" not in request.files:
return redirect(url_for("home"))
file = request.files["file"]
if file.filename == "":
return redirect(url_for("home"))
file.save(os.path.join(app.config["UPLOAD_FOLDER"], file.filename))
return redirect(url_for("home"))
@app.route("/download/<filename>")
def download_file(filename):
return send_from_directory(app.config["UPLOAD_FOLDER"], filename,
as_attachment=True)
if __name__ == "__main__":
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload & Download</title>
<link rel="stylesheet" href="https://unpkg.com/sakura.css/css/sakura.css" type="text/css">
</head>
<body>
<h1>Upload a File</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>
<h2>Download Files</h2>
<ul>
{% for file in files %}
<li><a href="{{ url_for('download_file', filename=file) }}">{{ file }}</a></li>
{% endfor %}
</ul>
</body>
</html>
Output:
Program - 4
Aim - A program that creates a web application that displays data from a
database in a tabular format.
Source Code:
import sqlite3
from flask import Flask, render_template
app = Flask(__name__)
def get_users():
conn = sqlite3.connect("data.db")
cursor = conn.cursor()
cursor.execute("SELECT id, name, email FROM users")
users = cursor.fetchall()
conn.close()
return users
@app.route("/")
def index():
users = get_users()
return render_template("index.html", users=users)
if __name__ == "__main__":
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/sakura.css/css/sakura.css" type="text/css">
<title>Users Table</title>
</head>
<body>
<h1>User List</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user[0] }}</td>
<td>{{ user[1] }}</td>
<td>{{ user[2] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
Output:
Program - 5
Aim - A program that creates a web application that accepts user input and
sends it to a server-side script for processing.
Source Code:
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/sakura.css/css/sakura.css" type="text/css">
<title>User Input Form</title>
</head>
<body>
<h1>Enter Something</h1>
<form action="/" method="post">
<input type="text" name="user_input" required>
<button type="submit">Submit</button>
</form>
{% if result %}<h2>{{ result }}</h2>{% endif %}
</body>
</html>
Output:
Set - 4
Program - 1
Aim - A program that creates a web application that uses a template engine
to generate dynamic HTML pages.
Source Code:
ppfd/home/views.py
from django.shortcuts import render
def home(request):
context = {
"name": "Aatish",
"subjects": [
"Python Programming with Full Stack Development",
"Computer Networks",
"Operating System",
"Computer Organization and Microprocessor Architecture",
"Probability Statistics and Numerical",
"Professional Grooming and Personality Development"
],
}
return render(request, "index.html", context)
ppfd/home/templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sakura.css/css/sakura.css"
type="text/css">
</head>
<body>
<h1>Welcome, {{ name }}!</h1>
<h2>Your Subjects:</h2>
<ul>
{% for subject in subjects %}
<li>{{ subject }}</li>
{% endfor %}
</ul>
</body>
</html>
ppfd/home/urls.py
from django.urls import path
from .views import home
urlpatterns = [
path('', home, name='home')
]
Output:
Program - 2
Aim - A program that creates a web application that supports AJAX
requests and updates the page without reloading.
Source Code:
ppfd/home/views.py
from django.shortcuts import render
import json
from django.http import JsonResponse
def home(request):
return render(request, 'index.html')
def update_data(request):
if request.method == "POST":
data = json.loads(request.body)
new_item = data.get("new_item", "")
return JsonResponse({"message": "Item added successfully", "new_item": new_item})
return JsonResponse({"error": "Invalid request"}, status=400)
ppfd/home/urls.py
from django.urls import path
from .views import home,update_data
urlpatterns = [
path('', home),
path('update/', update_data, name='update_data'),
]
ppfd/home/templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Demo</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sakura.css/css/sakura.css"
type="text/css">
</head>
<body>
<h1>AJAX Demo</h1>
<input type="text" id="itemInput" placeholder="Enter new item">
<button onclick="addItem()">Add Item</button>
<ul id="itemList"></ul>
<script>
function addItem() {
let newItem = document.getElementById("itemInput").value;
fetch('/update/', {
method: 'POST',
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({ new_item: newItem })
}).then(response => response.json())
.then(data => {
let list = document.getElementById("itemList");
let li = document.createElement("li");
li.textContent = data.new_item;
list.appendChild(li);
}).catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
Output:
Program - 3
Aim - A program that creates a web application that uses Django’s built-in
debugging features to troubleshoot errors and exceptions.
Source Code:
ppfd/home/views.py
from django.shortcuts import render
def home(request):
return render(request, 'index.html')
ppfd/home/middleware.py
from django.utils.deprecation import MiddlewareMixin
class DebugMiddleware(MiddlewareMixin):
def process_request(self, request):
if 'error' in request.GET:
raise ValueError("This is a test error for debugging!")
ppfd/home/templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sakura.css/css/sakura.css"
type="text/css">
</head>
<body>
<h1>Welcome to Home App</h1>
<p>Trigger an error by adding '?error=1' to the URL.</p>
</body>
</html>
Output:
Program - 4
Aim - A program that creates a web application that implements user
authentication and authorization.
Source Code:
ppfd/home/views.py
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from .forms import RegisterForm
def home_view(request):
return render(request, "index.html", {"title": "Home"})
def register_view(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect("dashboard")
else:
form = RegisterForm()
return render(request, "register.html", {"form": form, "title": "Register"})
@login_required
def dashboard_view(request):
return render(request, "dashboard.html", {"title": "Dashboard"})
def logout_view(request):
logout(request)
return redirect("home")
ppfd/home/forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class RegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
ppfd/home/urls.py
from django.urls import path
from django.contrib.auth.views import LoginView
from .views import home_view, register_view, dashboard_view, logout_view
urlpatterns = [
path('', home_view, name='home'),
path('register/', register_view, name='register'),
path('login/', LoginView.as_view(template_name='login.html'), name='login'),
path('dashboard/', dashboard_view, name='dashboard'),
path('logout/', logout_view, name='logout'),
]
ppfd/home/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{page_title}}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sakura.css/css/sakura.css"
type="text/css">
</head>
<body>
{% block content %}{% endblock content %}
</body>
</html>
ppfd/home/templates/login.html
{% extends "base.html" %}
{% block content %}
<h1>Login</h1>
<form method="post">
{{ form.as_p }}
<button type="submit">Login</button>
</form>
<a href="{% url 'register' %}">Register</a>
{% endblock content %}
ppfd/home/templates/index.html
{% extends "base.html" %}
{% block content %}
<h1>Welcome to the Home Page</h1>
<a href="{% url 'login' %}">Login</a> | <a href="{% url 'register' %}">Register</a>
{% endblock content %}
ppfd/home/templates/dashboard.html
{% extends "base.html" %}
{% block content %}
<h1>Welcome to the Dashboard</h1>
<a href="{% url 'logout' %}">Logout</a>
{% endblock content %}
ppfd/home/templates/register.html
{% extends "base.html" %}
{% block content %}
<h1>Register</h1>
<form method="post">
{{ form.as_p }}
<button type="submit">Register</button>
</form>
<a href="{% url 'login' %}">Login</a>
{% endblock content %}
Output:
Program - 5
Aim - A program that creates a web application that integrates with
third-party APIs to provide additional functionality.
Source Code:
ppfd/home/views.py
from django.shortcuts import render
import requests
def home_view(request):
API_KEY = "85WNBE4Q3MBSVG62QMDNTK85X"
weather_data = None
error_message = None
if request.method == 'POST':
city = request.POST.get('city')
if city:
url =
f"https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/{city
}/today?unitGroup=metric&include=current&key={API_KEY}&contentType=json"
response = requests.get(url)
print(response)
if response.status_code == 200:
data = response.json()
weather_data = {
'city': data['address'],
'temperature': data['currentConditions']['temp'],
'description': data['days'][0]['description'],
'icon': data['days'][0]['icon']
}
else:
error_message = "City not found. Please try again."
ppfd/home/urls.py
from django.urls import path
from .views import home_view
urlpatterns = [
path('', home_view, name='home_view'),
]
ppfd/home/templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sakura.css/css/sakura.css"
type="text/css">
<style>body {text-align: center; } .weather-card { padding: 20px; border-radius: 10px;
background: #f3f3f3; display: inline-block; }</style>
</head>
<body>
<h1>Weather App</h1>
<form method="post">
<input type="text" name="city" placeholder="Enter city name" required>
<button type="submit">Get Weather</button>
</form>
{% if weather %}
<div class="weather-card">
<h2>{{ weather.city }}</h2>
<p>{{ weather.temperature }}°C</p>
<p>{{ weather.description }}</p>
<img src="/static/1st Set - Color/{{ weather.icon }}.svg" height="100px"
width="100px" alt="Weather Icon"></div>
{% endif %}{% if error %}
<p style="color: red;">{{ error }}</p>
{% endif %}
</body>
</html>
Output: