Python Practicals Set-1 & Set-2
Python Practicals Set-1 & Set-2
BACHELOR OF TECHNOLOGY
4th Semester
Computer Science & Engineering Department
Laboratory Manual
CERTIFICATE
Signature of HOD:
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
INDEX
Set-3
1. A program that creates a
simple web server and serves
a static HTML page.
2. A program that creates a web
application that allows users
to register and login.
3. A program that creates a web
application that allows users
3 to upload and download files.
4. A program that creates a web
application that displays data
from a database in a tabular
format.
5. A program that creates a web
application that accepts user
input and sends it to a server-
side script for processing.
Set-4
1. A program that creates a web
application that uses a
template engine to generate
dynamic HTML pages.
2. A program that creates a web
application that supports AJAX
requests and updates the page
without reloading.
3. A program that creates a web
application that uses Django's
4 built-in debugging features to
troubleshoot errors and
exceptions.
4. A program that creates a web
application that implements
user authentication and
authorization.
5. A program that creates a web
application that integrates
with third-party APIs to
provide additional
functionality.
PRACTICAL : 1
SET : 1
1. AIM: A program that converts temperatures from Fahrenheit to Celsius and vice
versa.
if choice=="1":
elif choice=="2":
celsuis=float(input("Enter temperature in celsuis:"))
fahrenheit=(celsuis*9/5)+32
else:
Output:
area=length*width
perimeter=2*(length+width)
Output:
import random
import string
def generate_password(length):
letters = string.ascii_letters
digits = string.digits
special_chars = string.punctuation
if length < 4:
return "Password length should be at least 4 to ensure complexity."
else:
password = [
random.choice(letters),
random.choice(digits),
random.choice(special_chars)
]
passwords = []
passwords += random.choices(all_chars, k=length - 3)
random.shuffle(password)
return ''.join(password)
try:
length = int(input("Enter the desired password length:"))
print(f"Generated Password: {generate_password(length)}")
except ValueError:
print("Please enter a valid number.")
Output:
def calculate_average(numbers):
if not numbers:
return"The list is empty. Cannot calculate the average."
total = sum(numbers)
count = len(numbers)
average = total/count
return average
try:
numbers = list(map(float, input("Enter the numbers separated by spaces:").split()))
average = calculate_average(numbers)
print(f"The average is: {average}")
except ValueError:
print("Please enter valid numbers.")
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:"))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
except ValueError:
print("Please enter a valid year.")
Output:
def factorial(n):
if n<0:
Output:
if string == string[::-1]:
print(f'"{string}" is a palidrome.')
else:
Output:
numbers.sort()
print("Numbers sorted in ascending order.", numbers)
elif choice == "2":
numbers.sort(reverse = True)
print("Numbers sorted in descending order.", numbers)
else:
Output:
number = int(input("Enter the number up to which you want the table: "))
Output:
10. Aim: A program that converts a given number from one base to another.
def to_decimal(number,base):
return int(str(number),base)
def from_decimal(number,base):
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
result = ""
while number > 0:
result = digits[number % base] + result
number = number // base
return result or "0"
except ValueError:
Output:
PRACTICAL : 2
SET : 2
1. AIM: A program that models a bank account, with classes for the account, the customer,
and the bank.
class Account:
def init (self, account_number, balance=0):
self.account_number = account_number
self.balance = balance
def get_balance(self):
return self.balance
class Customer:
def init (self, name, customer_id):
self.name = name
self.customer_id = customer_id
self.accounts = []
def list_accounts(self):
for account in self.accounts:
print(f'Account Number: {account.account_number}, Balance: {account.balance}')
class Bank:
def init (self, name):
self.name = name
self.customers = []
def list_customers(self):
print(f"Customers of {self.name}:")
for customer in self.customers:
print(f"Name: {customer.name}, Customer ID: {customer.customer_id}")
customer1.add_account(account1)
customer2.add_account(account2)
Output:
2. Aim: A program that simulates a school management system, with classes for the
students, the teachers, and the courses.
class Student:
def init (self, name, student_id):
self.name = name
self.student_id = student_id
self.courses = []
def list_courses(self):
print(f"Courses for {self.name}:")
for course in self.courses:
print(f" - {course.name} (Code: {course.course_code})")
class Teacher:
def init (self, name, teacher_id):
self.name = name
self.teacher_id = teacher_id
self.courses = []
def assign_course(self, course):
self.courses.append(course)
print(f"Teacher {self.name} assigned to course {course.name}.")
def list_courses(self):
print(f"Courses taught by {self.name}:")
for course in self.courses:
print(f" - {course.name} (Code: {course.course_code})")
class Course:
def init (self, name, course_code):
self.name = name
self.course_code = course_code
self.students = []
self.teacher = None
def assign_teacher(self, teacher):
self.teacher = teacher
2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
course1.assign_teacher(teacher1)
course2.assign_teacher(teacher2)
teacher1.assign_course(course1)
teacher2.assign_course(course2)
course1.enroll_student(student1)
course2.enroll_student(student2)
student1.enroll(course1)
student2.enroll(course2)
teacher1.list_courses()
teacher2.list_courses()
print("\n-- Student Details --")
student1.list_courses()
student2.list_courses()
Output:
3. Aim: A program that reads a text file and counts the number of words in it.
try:
content = file.read()
words = content.split()
word_count = len(words)
except FileNotFoundError:
print(f"The file '{file_name}' was not found. Please check the file try again.")
Output:
import csv
try:
total = 0
count = 0
for row in csv_reader:
try:
total += float(row[column_name])
count += 1
except ValueError:
except KeyError:
break
if count > 0:
else:
except FileNotFoundError:
print(f"The file '{file_name}' was not found. Please check the file name and try again.")
Output:
5. Aim : A program that reads an Excel file and prints the data in a tabular format.
Source Code:
import pandas as pd
file_name = r'./jay.xlsx'
try:
data = pd.read_excel(file_name,engine='openpyxl')
print("\nData in the Excel file:")
print(data.to_markdown(index=False))
except FileNotFoundError:
print(f"File '{file_name}' not found.")
except PermissionError:
print(f"Permission denied to open '{file_name}'.")
Output:
PRACTICAL : 3
SET : 3
1. Aim : A program that creates a simple web server and serves a static HTML page.
Python code:
HTML CODE :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Web Server</title>
</head>
<body>
<h1>Welcome to My Simple Web Server!</h1>
<p>This is a static HTML page served by a Python web server.</p>
</body>
</html>
Output :
2. Aim: A program that creates a web application that allows users to register and login.
Python Code:
from flask import Flask, render_template, request, redirect, url_for, flash
import sqlite3
app = Flask( name )
app.secret_key = 'your_secret_key'
# Database setup
def init_db():
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)
''')
conn.commit()
conn.close()
@app.route("/")
def home():
return render_template('home.html')
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username,
password))
conn.commit()
flash("Registration successful! Please log in.", "success")
return redirect(url_for("login"))
except sqlite3.IntegrityError:
flash("Username already exists. Please choose a different one.", "error")
finally:
conn.close()
return render_template("signup.html")
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome to the web Application</h1>
<a href="/register">Register</a> | <a href="/login">Login</a>
</body>
</html>
HTML Register:
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<h1>Register</h1>
{% with messages = get_flashed_messages(with_categories=true) %}
{% for category, message in messages %}
HTML Login:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
{% with messages = get_flashed_messages(with_categories=true) %}
{% for category, message in messages %}
HTML Dashborad:
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h1>Welcome, {{ username }}</h1>
<a href="/logout">Logout</a>
</body>
</html>
Home Page:
3. Aim: A program that creates a web application that allows users to upload and download
files.
Python Code:
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
if file:
filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename) file.save(filepath)
return redirect(url_for('home'))
<!doctype html>
<html>
<head>
<title>File Upload and Download</title>
</head>
<body>
<h1>Upload and Download Files</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
<h2>Files:</h2>
<ul>
{% for file in files %}
<li><a href="{{ url_for('download_file', filename=file) }}">{{ file }}</a></li>
{% endfor %}
</ul>
</body>
</html>
Output :
4. Aim: A program that creates a web application that displays data from a database in a
tabular format.
Python Code:
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Employee Table</title>
<style>
table {
width: 80%; margin: 20px auto;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd; padding: 10px;
text-align: center;
}
th {
background-color: #f4f4f4;
}
</style>
</head>
<body>
<h1 style="text-align: center;">Employee Data</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
{% for employee in employees %}
<tr>
<td>{{ employee[0] }}</td>
<td>{{ employee[1] }}</td>
<td>{{ employee[2] }}</td>
Output:
5. Aim: A program that creates a web application that accepts user input and sends it to a
server- side script for processing.
Python Code:
# Route for the home page with the input form @app.route("/", methods=["GET",
"POST"]) def index():
if request.method == "POST":
# Process the input (in this case, reverse the string) processed_data = user_input[::-1]
HTML Code:
Input.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Input Form</title>
</head>
<body>
<h1>Enter a String</h1>
<form method="POST">
<label for="user_input">Your Input:</label>
<input type="text" id="user_input" name="user_input" required>
<button type="submit">Submit</button>
2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
</form>
</body>
</html>
Result.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Processed Result</title>
</head>
<body>
<h1>Processed Result</h1>
<p><strong>Original Input:</strong> {{ original }}</p>
<p><strong>Processed Output:</strong> {{ result }}</p>
<a href="/">Go Back</a>
</body>
</html>
Output:
1. Aim: A program that creates a web application that uses a template engine to generate
dynamicHTML pages.
Python Code:
HTML Code:
from flask import Flask, render_template app = Flask( name )
@app.route("/") def home():
# Data to be passed to the template items = [
{"name": "Apple", "price": "$1.00"},
{"name": "Banana", "price": "$0.50"},
{"name": "Cherry", "price": "$2.00"},
{"name": "Date", "price": "$3.00"},
{"name": "Elderberry", "price": "$4.50"},
]
Output:
2. Aim: A program that creates a web application that supports AJAX requests and updates
the page without reloading.
ajax_app/
├── app.py # Flask application
├── static/ │ └── script.js # JavaScript for handling AJAX
├── templates/ │ ├── index.html # Main HTML file app.py
from flask import Flask, render_template, request, jsonify app = Flask( name )
# Data storage (simulating a database) items = []
script.js
$(document).ready(function () {
$("#add-item-form").on("submit", function (e) { e.preventDefault(); // Prevent form from
reloading the page
const newItem = $("#item-input").val().trim(); if (newItem) {
$.ajax({
url: "/add_item", type: "POST",
2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
contentType: "application/json",
data: JSON.stringify({ item: newItem }), success: function (response) {
if (response.success) { updateList(response.items);
$("#item-input").val(""); // Clear input field
} else {
alert(response.error || "An error occurred.");
}
},
error: function () {
alert("Failed to communicate with the server.");
},
});
} else {
alert("Please enter an item.");
}
});
Output:
3. Aim: A program that creates a web application that uses Django's built-in debugging
features to troubleshoot errors and exceptions.
Steps:
1. Install Django (if not installed)
pip install django
def trigger_error(request):
"""This function intentionally triggers an error to test debugging.""" x = 1 / 0 # This will
cause a ZeroDivisionError
return HttpResponse("This will never be reached.")
6. Configure URLs
Edit debug_app/urls.py:
from django.urls import path from .views import trigger_error urlpatterns = [
4. Aim: A program that creates a web application that implements user authentication
and authorization.
Steps:
1. Install Django pip install django
2. Create a Django Project
django-admin startproject auth_project cd auth_project
3. Create an App
python manage.py startapp accounts
4. Configure urls.py
Edit auth_project/urls.py:
from django.contrib import admin from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('accounts.urls')), # Include authentication routes
]
5. Create User Authentication Views
from django.shortcuts import render, redirect
from django.contrib.auth import login, logout, authenticate from
django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth.decorators import login_required
def register(request):
if request.method == "POST":
username = request.POST['username'] password = request.POST['password']
confirm_password = request.POST['confirm_password']
2403031057133 (MAHEK SURTI)
PARUL UNIVERSITY
FACULTY OF ENGINEERING AND TECHNOLOGY
PROGRAMMING IN PYTHON WITH FULL
STACK DEVELOPMENT (303105258)
B. TECH. 2ND YEAR
if password != confirm_password: messages.error(request, "Passwords do not match!")
return redirect('register')
if User.objects.filter(username=username).exists(): messages.error(request, "Username
already exists!") return redirect('register')
user = User.objects.create_user(username=username, password=password) user.save()
messages.success(request, "Registration successful! Please log in.") return redirect('login')
return render(request, "register.html")
def user_login(request):
if request.method == "POST":
@login_required
def dashboard(request):
return render(request, "dashboard.html")
6. Set Up URLs Set Up URLs
from django.urls import path
from .views import register, user_login, user_logout, dashboard
1. Aim: A program that creates a simple RESTful API that returns a list of users in JSON
format.
app = FastAPI()
Output: