Python Lab
Python Lab
TECHNOLOGY
LAB MANUAL
CERTIFICATE
Date of Submission:
INDEX
Set / TITLE Start End Start End Marks Sign
SR. Page Page Date Date out of 10
No. No. No.
SET – 1 : Python Programming Basics
Practical 1 :
Aim
To write a Python program that converts temperature from Fahrenheit to Celsius and vice
versa.
Algorithm
1. Input temperature value
2. Ask user for conversion choice
3. Apply appropriate formula
4. Display the converted temperature
Program
temp = float(input("Enter temperature: "))
choice = input("Convert to (C/F): ")
if [Link]() == 'C':
c = (temp - 32) * 5 / 9
print("Temperature in Celsius:", c)
elif [Link]() == 'F':
f = (temp * 9 / 5) + 32
print("Temperature in Fahrenheit:",
f) else:
print("Invalid choice")
Output
Enter temperature: 98
Convert to (C/F): C
Temperature in Celsius: 36.66
Practical 2
Aim
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
area = l * b
perimeter = 2 * (l + b)
print("Area:", area)
print("Perimeter:", perimeter)
Output
Area: 50
Perimeter: 30
Practical 3
Aim
To generate a random password of specified length.
Algorithm
1. Input password length
2. Use letters, digits, and symbols
3. Generate random characters
4. Display password
Program
import random
import string
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
Practical 4
Aim
To calculate the average of a list of numbers.
Algorithm
1. Input numbers as a list
2. Find sum of list
3. Divide by number of elements
4. Display average
Program
nums = list(map(int, input("Enter numbers: ").split()))
avg = sum(nums) / len(nums)
print("Average:", avg)
Output
Enter numbers: 10 20 30
Average: 20.0
Practical 5
Aim
To check whether a given year is a leap year.
Algorithm
1. Input year
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
Practical 6
Aim
To calculate factorial of a given number.
Algorithm
1. Input number
2. Multiply numbers from 1 to n
3. Display factorial
Program
n = int(input("Enter number: "))
fact = 1
print("Factorial:", fact)
Output
Enter number: 5
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
Factorial: 120
Practical 7
Aim
To check whether a string is a palindrome.
Algorithm
1. Input string
2. Reverse the string
3. Compare original and reversed
4. Display result
Program
s = input("Enter string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")
Output
Enter string: madam
Palindrome
Practical 8
Aim
To sort a list of numbers in ascending or descending order.
Algorithm
1. Input list
2. Ask sorting order
3. Sort accordingly
4. Display result
Program
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
if order == "asc":
[Link]()
else:
[Link](reverse=True)
Practical 9
Aim
To generate a multiplication table for a given number.
Algorithm
1. Input number
2. Loop from 1 to 10
3. Print multiplication
Program
n = int(input("Enter number: "))
Practical 10
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
Aim
To convert a given number from one base to another.
Algorithm
1. Input number and base
2. Convert using built-in functions
3. Display result
Program
num = int(input("Enter number: "))
print("Binary:", bin(num))
print("Octal:", oct(num))
print("Hexadecimal:", hex(num))
Output
Binary: 0b1010
Octal: 0o12
Hexadecimal: 0xa
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
Practical 1
Aim
To model a bank account system using classes for Account, Customer, and Bank.
Algorithm
1. Create Customer class
2. Create Account class with deposit & withdraw
3. Create Bank class to manage accounts
4. Perform operations
Program
class Customer:
def init (self, name):
[Link] = name
class Account:
def init (self, acc_no, balance):
self.acc_no = acc_no
[Link] = balance
[Link] -= amt
else:
print("Insufficient Balance")
class Bank:
def init (self):
[Link] = []
def
add_account(self,acco
unt):
[Link]
account)
cust = Customer("Aryan")
acc = Account(101, 5000)
[Link](2000)
[Link](1000)
print("Final Balance:", [Link])
Output
Final Balance: 6000
Practical 2
Aim
To simulate a school management system using classes.
Algorithm
1. Create Student, Teacher, Course classes
2. Assign course to students
3. Display details
Program
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
class Teacher:
def init (self, name):
[Link] = name
class Course:
def init (self, cname):
[Link] = cname
s = Student("Ravi")
t = Teacher("[Link]")
c = Course("Python")
print("Student:", [Link])
print("Teacher:", [Link])
print("Course:", [Link])
Output
Student: Ravi
Teacher: Mr. Sharma
Course: Python
Practical 3
Aim
To read a text file and count the number of words in it.
Algorithm
1. Open text file
2. Read content
3. Split words
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
4. Count words
Program
file = open("[Link]", "r")
text = [Link]()
words = [Link]()
print("Word Count:",len(words))
[Link]()
Output
Word Count: 45
Practical 4
Aim
To read a CSV file and calculate the average of values in a specified column.
Algorithm
1. Open CSV file
2. Read values from column
3. Calculate average
4. Display result
Program
import csv
Practical 5
Aim
To read an Excel file and display data in tabular format.
Algorithm
1. Load Excel file
2. Read rows
3. Print data
Program
import openpyxl
wb = openpyxl.load_workbook("[Link]")
sheet = [Link]
Practical 1
Aim
To create a simple web server and serve a static HTML page.
Algorithm
1. Install Flask
2. Create Flask app
3. Define route
4. Serve HTML page
Program
from flask import Flask
@[Link]("/")
def home():
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
Practical 2
Aim
To create a web application that allows users to register and login.
Algorithm
1. Create registration form
2. Store username & password
3. Validate login credentials
4. Display result
Program
from flask import Flask, request
@[Link]("/register", methods=["POST"])
def register():
users[[Link]['username']] = [Link]['password']
return "Registered Successfully"
@[Link]("/login", methods=["POST"])
def login():
if [Link]([Link]['username']) == [Link]['password']:
return "Login Successful"
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
Practical 3
Aim
To create a web application that allows users to upload and download files.
Algorithm
1. Accept file from user
2. Save file on server
3. Allow file download
Program
from flask import Flask, request
@[Link]("/upload", methods=["POST"])
def upload():
file = [Link]['file']
[Link]([Link])
return "File Uploaded Successfully"
Practical 4
Aim
To display data from a database in tabular format using a web application.
Algorithm
1. Connect to database
2. Fetch records
3. Display in HTML table
Program
from flask import Flask import
sqlite3
Practical 5 Aim
To create a web application that accepts user input and processes it on the server side.
Algorithm
1. Accept input from user
COMPUTER SCIENCE AND ENGINEERING
FACULTY OF ENGINEERING & TECHNOLOGY
PPFSD (303105257) -
B. TECH 4th SEM
ENROLLMENT NO: 2403031461270
2. Process input
3. Display result
Program
from flask import Flask, request
@[Link]("/square", methods=["POST"])
def square():
num = int([Link]['number'])
return f"Square is {num*num}"
SET-4
PRACTICAL-1
AIM : A program that creates a web application that uses a template engine
to generate dynamic HTML pages.
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Page</title>
</head>
<body>
<div style="background-color:cadetblue">
<h1 style="color: black;">This is HTML page.</h1>
</div>
</body>
</html>
[Link]
from [Link] import render
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270
[Link]
from [Link] import path
from . import views
urlpatterns = [
path('', [Link], name='index'),
]
OUTPUT:
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270
PRACTICAL- 2
CODE:
[Link]
<!DOCTYPE html>
<html>
<head>
<title>AJAX Demo</title>
</head>
<body>
<h2>AJAX Example</h2>
<button onclick="loadData()">Click Me</button>
<p id="result"></p>
<script>
function loadData() {
fetch('/get-data/')
.then(response => [Link]())
.then(data => {
[Link]("result").innerHTML = [Link];
});
}
</script>
</body>
</html>
[Link]
from [Link] import render
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270
from [Link] import JsonResponse
def get_data(request):
return JsonResponse({"message": "Hello! Page updated without reload..!"})
[Link]
from [Link] import path
from . import views
urlpatterns = [
path('', [Link], name='home'),
path('get-data/', views.get_data),
]
OUTPUT:
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270
PRACTICAL- 3
AIM: A program that creates a web application that uses Django's built-in
debugging features to troubleshoot errors and exceptions.
CODE:
[Link]
def trigger_error(request):
x = 10 / 0 # Intentional error (ZeroDivisionError)
return HttpResponse("This will never run")
[Link]
urlpatterns = [
path('', [Link]),
path('error/', views.trigger_error),
]
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270
OUTPUT:
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270
PRACTICAL- 4
AIM: A program that creates a web application that implements user
authentication and Authorization.
CODE:
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Website</title>
<link rel="stylesheet" href="../static/css/[Link]">
</head>
<body>
<div class="navbar">
<a href="/">Home</a>
<a href="/about/">About</a>
<a href="/join/">Join Us</a>
<a href="/logout/">Logout</a>
</div>
<div class="header">
<h1>Welcome</h1>
</div>
<br>
<div class="content">
<h2 class="contentText">About</h2>
<p class="contentText">This website is created using basic HTML tags and
CSS.</p>
<a href="/about/"><button class="btn">Go to about page</button></a>
</div>
</body>
</html>
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
ENROLLMENT NO: 2403031461270
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signup</title>
<link rel="stylesheet" href="../static/css/[Link]">
</head>
<body>
<div class="content">
<h1>Signup</h1><br><br>
{% if messages %}
<div>
{% for msg in messages %}
{{ msg }}
{% endfo %}
</div>
{% endif %}
<form action="/signup/" method="POST" class="contentText">
{% csrf_token %}
<label for="email">Email: </label>
<input type="email" name="email"><br><br>
<label for="password">Password: </label>
<input type="password" name="password"><br><br>
<label for="password">Confirm Password: </label>
<input type="password" name="confirmPassword"><br><br>
<button type="submit" class="btn">Submit</button>
</form>
<p class="contentText">Already have an account?</p>
<a href="login" class="contentText">Login here</a><br><br>
</div>
</body>
</html>
[Link]
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="../static/css/[Link]">
</head>
<body>
<div class="content">
<h1>Login</h1><br><br>
{% if messages %}
<div>
{% for msg in messages %}
{{ msg }}
{% endfor %}
</div>
{% endif %}
<form action="/login/" method="POST"
class="contentText">
{% csrf_token %}
<label for="email">Email: </label>
<input type="email" name="email"><br><br>
<label for="password">Password: </label>
<input type="password" name="password"><br><br>
<button type="submit" class="btn">Submit</button>
</form>
<p class="contentText">Don't have an account ?</p>
<a href="signup" class="contentText">Signup
here</a><br><br>
</div>
</body>
</html>
[Link]
.navbar{
background-color: #170503;
font-size: 23px;
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
text-align: center;
padding: 10px;
}
.navbar a{
color: white;
margin: 0 15px;
font-weight: bold;
text-decoration: none;
}
.navbar a:hover{
text-decoration: underline;
}
.header {
background-color: #9c7b5f;
text-align: center;
padding: 20px;
color: white;
}
.content{
background-color: #9c7b5f;
padding: 20px;
margin: 20px;
color: white;
}
.contentText{
color: white;
}
.btn{
background-color: #9c7b5f;
padding: 10px;
cursor: pointer;
color: white;
border: none;
font-size: 15px;
}
.btn:hover{
background-color: #170503;
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
.input {
padding: 8px;
margin: 5px;
width: 250px;
}
[Link]
from [Link] import render, redirect
from [Link] import HttpResponse
from [Link] import connection
from .models import *
from [Link] import authenticate, login, logout
from [Link] import login_required
from [Link] import messages
from [Link] import User
@login_required(login_url='/login/')
def index(request):
return render(request, '[Link]')
def signup_page(request):
if [Link] == 'POST':
username = [Link]('email')
password = [Link]('password')
confirmPassword = [Link]('confirmPassword')
if password != confirmPassword:
[Link](request, "Passwords do not match.")
user = [Link](username=username)
if [Link]():
[Link](request, "User already exists.")
return redirect('/login/')
else:
user = [Link].create_user(username=username)
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
user.set_password(password)
[Link]()
return redirect('/login/')
return render(request, '[Link]')
def login_page(request):
if [Link] == "POST":
username = [Link]("email")
password = [Link]("password")
if not [Link](username=username).exists():
[Link](request, "Invalid email.")
return redirect('/login/')
user = authenticate(username=username,
password=password)
if user is None:
[Link](request, "Invalid credentials.")
return redirect('/login/')
else:
login(request, user)
return redirect('/index/')
return render(request, '[Link]')
@login_required(login_url='/login/')
def logout_page(request):
logout(request)
return redirect('/login/')
[Link]
urlpatterns = [
path("", views.signup_page, name="signup"),
path("signup/", views.signup_page, name="signup"),
path("login/", views.login_page, name="login"),
path("logout/", views.logout_page, name="logout"),
path("index/", [Link], name="index"),
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
OUTPUT:
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
PRACTICAL- 5
CODE:
[Link]
from flask import Flask, jsonify
import requests
@[Link]('/users')
def get_users():
response = [Link]("[Link]
data = [Link]()
return jsonify(data)
. .
Faculty of Engineering and Technology
Programming in Python with Full Stack
development(303105258)
[Link] CSE 2nd year 4th semester
OUTPUT:
. .
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
SET-5
PRACTICAL-1
AIM : A program that creates a simple RESTful API that returns a list of
users in JSON format
CODE:
data = [
{"name": "abc", "enrollment_number": 12345, "age": 19},
{"name": "pqr", "enrollment_number": 67890, "age": 20}
]
@[Link]('/user', methods=['GET'])
def get_user():
return jsonify(data)
.
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
OUTPUT:
.
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
PRACTICAL- 2
AIM: A program that creates a RESTful API that allows users to create,
read, update, and delete resource
CODE:
[Link]
data = [
{"name": "abc", "enrollment_number": 12345, "age": 19},
{"name": "pqr", "enrollment_number": 67890, "age": 20}
]
# GET
@[Link]('/user', methods=['GET'])
def get_user():
return jsonify(data)
# POST
@[Link]('/user', methods=['POST'])
def add_user():
new_user = [Link]
[Link](new_user)
return jsonify({"message": "User added", "data": data})
# PUT
@[Link]('/user/<int:enrollment_number>', methods=['PUT'])
def update_user(enrollment_number):
for user in data:
if user['enrollment_number'] == enrollment_number:
user['name'] = [Link]('name', user['name'])
user['age'] = [Link]('age', user['age'])
return jsonify({"message": "User updated", "data": user})
. .
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
# DELETE
@[Link]('/user/<int:enrollment_number>', methods=['DELETE'])
def delete_user(enrollment_number):
for i in range(len(data)):
if data[i]["enrollment_number"] == enrollment_number:
deleted_user = [Link](i)
return jsonify({
"message": "Student deleted successfully",
"deleted_student": deleted_user
})
OUTPUT:
. .
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
PRACTICAL- 3
AIM: A program that creates a RESTful API that authenticates users using a
JSON Web Token
CODE:
[Link]
SECRET_KEY = "mysecret"
# Protected route
@[Link]('/profile')
def profile():
token = [Link]("Authorization")
try:
data = [Link](token, SECRET_KEY, algorithms=["HS256"])
return jsonify({"message": "Welcome " + data["user"]})
except:
return jsonify({"message": "Invalid or missing token"}), 403
. .
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
OUTPUT:
. .
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
PRACTICAL- 4
AIM: A program that creates a RESTful API that paginates the results of a
query to improve performance
CODE:
[Link]
# Sample data
users = [
{"id": 1, "name": "A"},
{"id": 2, "name": "B"},
{"id": 3, "name": "C"},
{"id": 4, "name": "D"},
{"id": 5, "name": "E"},
{"id": 6, "name": "F"},
{"id": 7, "name": "G"},
{"id": 8, "name": "H"},
{"id": 9, "name": "I"},
{"id": 10, "name": "J"}
]
@[Link]('/users', methods=['GET'])
def get_users():
page = int([Link]('page', 1))
per_page = int([Link]('per_page', 3))
paginated_users = users[start:end]
return jsonify(paginated_users)
. .
Faculty of Engineering and Technology
Programming in Python Full Stack
(303105258)
[Link] CSE 2nd year 4th semester
OUTPUT:
. .
PRACTICAL- 5
CODE:
[Link]
users = []
@[Link]('/users', methods=['POST'])
def add_user():
try:
data = request.get_json()
# Validation
if not [Link]("name"):
return jsonify({"error": "Name is required"}), 400
if not [Link]("age"):
return jsonify({"error": "Age is required"}), 400
user = {
"name": data["name"],
"age": data["age"]
}
[Link](user)
. .
return jsonify({
"message": "User added successfully",
"user": user
}), 201
except Exception as e:
return jsonify({"error": str(e)}), 500
@[Link]('/users', methods=['GET'])
def get_users():
return jsonify(users)
OUTPUT:
. .
. .