0% found this document useful (0 votes)
21 views38 pages

PPFD - Practicals

Mr. AATISHKUMAR B. PRASAD has successfully completed laboratory experiments in Programming in Python with Full Stack Development during the academic year 2024/25. The document includes various programming tasks such as temperature conversion, area and perimeter calculation, random password generation, and more, demonstrating practical applications of Python. Each task is accompanied by source code and expected outputs.

Uploaded by

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

PPFD - Practicals

Mr. AATISHKUMAR B. PRASAD has successfully completed laboratory experiments in Programming in Python with Full Stack Development during the academic year 2024/25. The document includes various programming tasks such as temperature conversion, area and perimeter calculation, random password generation, and more, demonstrating practical applications of Python. Each task is accompanied by source code and expected outputs.

Uploaded by

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

CERTIFICATE

This is to certify that Mr. AATISHKUMAR B. PRASAD

with enrolment number 2403031057107 has successfully

completed his laboratory experiments in

Programming in Python with Full Stack Development

Laboratory

during the academic year 2024/25.

Date: __________ Signature of Lab Teacher

Signature of HOD: ______________


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

2. Aim - A program that calculates the area and perimeter of a rectangle.


Source Code:

def calculate_area(length, width):


return length * width

def calculate_perimeter(length, width):


return 2 * (length + width)

print("Rectangle Area and Perimeter Calculator")

try:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))

if length <= 0 or width <= 0:


print("Length and width must be positive numbers.")
else:
area = calculate_area(length, width)
perimeter = calculate_perimeter(length, width)
print(f"\nThe area of the rectangle is: {area:.2f}")
print(f"The perimeter of the rectangle is: {perimeter:.2f}")

except ValueError:
print("Invalid input. Please enter numeric values.")

Output:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

3. Aim - A program that generates a random password of a specified


length.
Source Code:

import random

length = int(input("Enter the desired password length: "))

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

4. Aim - A program that calculates the average of a list of numbers.


Source Code:

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

5. Aim - A program to check if a given year is a leap year.


Source Code:

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

6. Aim - A program that calculates the factorial of a number.


Source Code:

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

7. Aim - A program that checks if a given string is a palindrome.


Source Code:

def is_palindrome(string):
nospace_string = string.replace(" ", "").lower()
return nospace_string == "".join(reversed(nospace_string))

string = input("Enter a string: ")

if is_palindrome(string):
print(f"'{string}' is a palindrome.")
else:
print(f"'{string}' is not a palindrome.")

Output:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

8. Aim - A program that sorts a list of numbers in ascending or descending


order.
Source Code:

def sort_numbers(numbers, order="asc"):


if order == "asc":
return sorted(numbers)
elif order == "desc":
return sorted(numbers, reverse=True)
else:
print("Invalid order specified. Use 'asc' or 'desc'.")
return numbers

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

9. Aim - A program that generates a multiplication table for a given


number.
Source Code:

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

10. Aim - A program that converts a given number from one base to
another.
Source Code:

def convert_base(number, from_base, to_base):


decimal_number = int(str(number), from_base)
if to_base == 10:
return decimal_number
result = ""
while decimal_number > 0:
result = str(decimal_number % to_base) + result
decimal_number //= to_base

return result if result else "0"

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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 = []

def add_customer(self, customer):


self.customers.append(customer)

def add_account(self, account):


self.accounts.append(account)

def get_customer_accounts(self, customer):


return [acc for acc in self.accounts if acc.customer == customer]

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 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):

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

if 0 < amount <= self.balance:


self.balance -= amount
print(f"Withdrawn {amount}. New balance: {self.balance}")
else:
print("Insufficient balance or invalid amount.")

def get_balance(self):
return self.balance

bank = Bank("SBI")
customer1 = Customer("Aatish", 1001)
bank.add_customer(customer1)

account1 = Account("A1001", customer1, 50000.0)


bank.add_account(account1)

print(f"Bank Name: {bank.name}")


print(f"Customer: {customer1.name}")

account1.deposit(25000)
account1.withdraw(15000)
print(f"Final Balance: {account1.get_balance()}")

Output:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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 = []

def add_student(self, student):


self.students.append(student)

def add_teacher(self, teacher):


self.teachers.append(teacher)

def add_course(self, course):


self.courses.append(course)

class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self.courses = []

def enroll(self, course):


self.courses.append(course)

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)

class Course:
def __init__(self, name, course_id, teacher):
self.name = name

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

self.course_id = course_id
self.teacher = teacher
self.students = []

def add_student(self, student):


self.students.append(student)

school = School("PIET")
teacher1 = Teacher("Arunesh Singh", 101)
student1 = Student("Aatish", 107)

course1 = Course("Python Programming", "PPFD101", teacher1)


teacher1.assign_course(course1)
school.add_teacher(teacher1)
school.add_student(student1)
school.add_course(course1)

student1.enroll(course1)
course1.add_student(student1)

print(f"School Name: {school.name}")


print(f"Teacher: {teacher1.name} teaches {course1.name}")
print(f"Student: {student1.name} enrolled in {course1.name}")

Output:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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

with open(csv_file, mode='r') as file:


reader = csv.DictReader(file)

for row in reader:


try:
total += float(row[column_name])
count += 1
except ValueError:
print(f"Warning: Could not convert {row[column_name]} to float.")
except KeyError:
print(f"Error: Column '{column_name}' not found in the CSV file.")
return None

if count == 0:
print("No valid entries found.")
return None

average = total / count


return average

csv_file = input("Enter csv filename: ")


column_name = input("Enter column name: ")
average_score = calculate_average(csv_file, column_name)

if average_score is not None:


print(f"The average {column_name} is: {average_score:.2f}")

Output:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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 = Flask(__name__, static_folder="static")

@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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

Program - 2
Aim - A program that creates a web application that allows users to
register and login.
Source Code:

from flask import Flask, render_template, request, flash, redirect, url_for


import sqlite3

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()

if (user and password==user[3]):


flash('Login successful!', 'success')
return redirect(url_for('index'))
else:
flash('Invalid email or password.', 'danger')

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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 %}

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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 %}

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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)

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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)

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:

from flask import Flask, request, render_template


app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def index():
result = None
if request.method == "POST":
user_input = request.form["user_input"]
result = f"You entered: {user_input}"
return render_template("index.html", result=result)​
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>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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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>

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

ppfd/home/urls.py
from django.urls import path
from .views import home

urlpatterns = [
path('', home, name='home')
]

Output:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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'),
]

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:​

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:​

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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']

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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 %}​

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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."

return render(request, 'index.html', {'weather': weather_data, 'error': error_message})

ppfd/home/urls.py​
from django.urls import path
from .views import home_view

urlpatterns = [
path('', home_view, name='home_view'),
]

AATISHKUMAR B. PRASAD CSE14 | 2403031057107


Faculty Of Engineering &Technology
Programming in Python with Full Stack
Development Laboratory (303105258)
B.Tech CSE 2nd Year 4th Semester

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:

AATISHKUMAR B. PRASAD CSE14 | 2403031057107

You might also like