0% found this document useful (0 votes)
18 views

PYTHON programs

Several python and Linux programs

Uploaded by

ca-684
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)
18 views

PYTHON programs

Several python and Linux programs

Uploaded by

ca-684
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/ 62

………………. ……………….

3.Write a program to reverse a number, sum of digits in the given number.

SOURCCE CODE :

def reverse_number(n):
return int(str(n)[::-1])

def sum_of_digits(n):
return sum(int(digit) for digit in str(n))

num = int(input("Enter a number: "))

reversed_num = reverse_number(num)
sum_of_digits_num = sum_of_digits(num)

print("Reversed number:", reversed_num)


print("Sum of digits:", sum_of_digits_num)

OUTPUT :
………………. ……………….

5.Python Program for Sum of squares of first n natural numbers


SOURCE CODE :
def sum_of_squares(n):
return sum(i**2 for i in range(1, n+1))

n = int(input("Enter a number: "))


result = sum_of_squares(n)
print("Sum of squares of first", n, "natural numbers is:", result)

OUTPUT :
………………. ……………….

6.Write a program to input a line of text . Write functions which takes text
as argument and
a. Calculate how many words starts with letter ‘t’.
b. Calculate how many words ends with the letter ‘s’.
c. Calculate how many 6 letters words are appearing.
d. Calculates how many words are there in the given text.
SOURCE CODE :
def count_words_starting_with_t(text):
words = text.split()
count = 0
for word in words:
if word[0].lower() == 't':
count += 1
return count
def count_words_ending_with_s(text):
words = text.split()
count = 0
for word in words:
if word[-1].lower() == 's':
count += 1
return count
def count_6_letter_words(text):
words = text.split()
count = 0
for word in words:
if len(word) == 6:
count += 1
return count
def count_total_words(text):
………………. ……………….

return len(text.split())
text = input("Enter a line of text: ")
print("Words starting with 't':", count_words_starting_with_t(text))
print("Words ending with 's':", count_words_ending_with_s(text))
print("6-letter words:", count_6_letter_words(text))
print("Total words:", count_total_words(text))

OUTPUT :
………………. ……………….

7.To count the number occurrences of each word in a sentence(use dict)


SOURCE CODE :
def word_count(input_str):
counts = dict()
words = input_str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
user_input = input("Enter a sentence: ")
result = word_count(user_input)
print(result)

OUTPUT :
………………. ……………….

8.To count the total number of vowels and consonants in the string.
SOURCE CODE :
str1 = input("Please Enter A String : ")
vowels = 0
consonants = 0
for i in str1:
if(i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u'
or i == 'A' or i == 'E' or i == 'I' or i == 'O' or i == 'U'):
vowels = vowels + 1
else:
consonants = consonants + 1
print("Total Number of Vowels in this String = ", vowels)
print("Total Number of Consonants in this String = ", consonants)

OUTPUT :
………………. ……………….

10.Find the most repeated word in a text file.


SOURCE CODE :
file_name = input("Enter the name of the text file (e.g., 'gfg.txt'): ")
try:
with open(file_name, "r") as file:
words = []
for line in file:
line_words = line.lower().replace(',', '').replace('.', '').split()
words.extend(line_words)
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
frequent_word = max(word_counts, key=word_counts.get)
frequency = word_counts[frequent_word]
print("Most repeated word: %s" % frequent_word)
print("Frequency: %d" % frequency)
except FileNotFoundError:
print("The file '%s' was not found. Please check the file name and try again." %
file_name)

OUTPUT :
………………. ……………….

11.Write factorial program with and without recursion


SOURCE CODE :
n=int(input("Enter number:"))
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ")
print(fact)

OUTPUT :
………………. ……………….

12.Program using if operations.


Compute the total quantity on hand for any one product and display .if it is <50
then “ time to place new order”>=50 and <100 “sufficient.>100 “Improve sales
and Python program to find sum of elements in list.
SOURCE CODE :
quantity = int(input("Enter the quantity of the product: "))
if quantity < 50:
print("Time to place new order.")
elif 50 <= quantity < 100:
print("Sufficient stock.")
else:
print("Improve sales.")

OUTPUT :
………………. ……………….

14.Write a program to evaluate a quadratic equation and find its roots. Catch
any exceptions that can be caught
SOURCE CODE :
import math
def evaluate_quadratic(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant < 0:
return "The equation has no real roots"
elif discriminant == 0:
return -b / (2*a)
else:
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
return root1, root2 # Two real roots
a = float(input("Enter coefficient 'a': "))
b = float(input("Enter coefficient 'b': "))
c = float(input("Enter coefficient 'c': "))
root = evaluate_quadratic(a, b, c)
if isinstance(root, str):
print(root)
elif isinstance(root, tuple):
print("The roots of the equation are %.2f and %.2f" % (root[0], root[1]))
else:
print("The root of the equation is %.2f" % root)
OUTPUT :
………………. ……………….

15.Program to display inbuilt errors of ZeroDivision ,Key Error, ValueError,


NameError
SOURCE CODE :
def divide_numbers():
try:
a = float(input("Enter the numerator: "))
b = float(input("Enter the denominator: "))
result = a / b
print("The result is: %s" % result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter valid numbers.")
def access_dictionary_key(dictionary):
try:
key = input("Enter the key to access: ")
value = dictionary[key]
print("The value of '%s' is: %s" % (key, value))
except KeyError:
print("Error: The key '%s' does not exist in the dictionary." % key)
def convert_string_to_int():
try:
string = input("Enter a string to convert to an integer: ")
number = int(string)
print("The integer value is: %s" % number)
except ValueError:
print("Error: The string cannot be converted to an integer.")
def access_undefined_variable():
try:
………………. ……………….

print("%s" % undefined_variable)
except NameError:
print("Error: The variable 'undefined_variable' is not defined.")
print("Testing ZeroDivisionError:")
divide_numbers()
print("\nTesting KeyError:")
dictionary = {"name": "John", "age": 30}
access_dictionary_key(dictionary)
print("\nTesting ValueError:")
convert_string_to_int()
print("\nTesting NameError:")
access_undefined_variable()

OUTPUT :
………………. ……………….

16.Computation of Tax with User defined Exception handling


SOURCE CODE :
class InvalidIncomeError(Exception):
pass
class InvalidTaxRateError(Exception):
pass
def compute_tax(income, tax_rate):
if income < 0:
raise InvalidIncomeError("Income cannot be negative")
if tax_rate < 0 or tax_rate > 1:
raise InvalidTaxRateError("Tax rate must be between 0 and 1")
tax = income * tax_rate
return tax
try:
income = float(input("Enter your income: "))
tax_rate = float(input("Enter the tax rate (as a decimal): "))
tax = compute_tax(income, tax_rate)
print("Your tax is: {tax:.2f}")
except InvalidIncomeError as e:
print("Error: {e}")
except InvalidTaxRateError as e:
print("Error: {e}")
except ValueError:
print("Error: Invalid input. Please enter a valid number.")
………………. ……………….

OUTPUT :
………………. ……………….

17.Program for basic classes and functions

SOURCE CODE :
# Define a class called "Animal"
class Animal:
def init (self, name, food):
self.name = name
self.food = food
def eat(self):
print("%s eats %s." % (self.name, self.food))
name = input("Enter the animal's name: ")
food = input("Enter the animal's food: ")
animal = Animal(name, food)
animal.eat()

OUTPUT :
………………. ……………….

18.Program for Inheritance


SOURCE CODE :
class Person:
def init (self, name):
self.name = name
def greet(self):
print("Hello, my name is {self.name}.")
class Student(Person):
def init (self, name, major):
super(). init (name)
self.major = major
def greet(self):
super().greet()
print("I'm studying {self.major}.")
name = input("Enter your name: ")
major = input("Enter your major: ")
my_student = Student(name, major)
my_student.greet()

OUTPUT :
………………. ……………….

21.Write a program to enter names and degrees of student and give the grades
according to the marks (use Dict)
SOURCE CODE :
students = {}
def add_student():
name = input("Enter student name: ")
degree = input("Enter student degree: ")
marks = float(input("Enter student marks: "))
if marks >= 90:
grade = "A"
elif marks >= 80:
grade = "B"
elif marks >= 70:
grade = "C"
elif marks >= 60:
grade = "D"
else:
grade = "F"
students[name] = {"Degree": degree, "Marks": marks, "Grade": grade}
def display_students():
for name, info in students.items():
print("Name: %s" % name)
print("Degree: %s" % info['Degree'])
print("Marks: %s" % info['Marks'])
print("Grade: %s" % info['Grade'])
print()
while True:
print("1. Add Student")
print("2. Display Students")
………………. ……………….

print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
add_student()
elif choice == 2:
display_students()
elif choice == 3:
break
else:
print("Invalid choice")

OUTPUT :
………………. ……………….

23.To add, subtract and multiply two matrices.


SOURCE CODE :
def get_matrix(rows, cols, matrix_name):
matrix = []
print("Enter elements for matrix " + matrix_name + ":")
for i in range(rows):
row = []
for j in range(cols):
row.append(int(input("Enter element [" + str(i+1) + "][" + str(j+1) + "]: ")))
matrix.append(row)
return matrix
def add_matrices(matrix1, matrix2):
result = [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] for i in
range(len(matrix1))]
return result
def subtract_matrices(matrix1, matrix2):
result = [[matrix1[i][j] - matrix2[i][j] for j in range(len(matrix1[0]))] for i in
range(len(matrix1))]
return result

# Function to multiply two matrices


def multiply_matrices(matrix1, matrix2):
result = [[sum(a * b for a, b in zip(row, col)) for col in zip(*matrix2)] for row in
matrix1]
return result
def print_matrix(matrix):
for row in matrix:
print(" ".join(str(x) for x in row)) # Just print the number without %
def main():
………………. ……………….

rows = int(input("Enter number of rows for the matrices: "))


cols = int(input("Enter number of columns for the matrices: "))
matrix1 = get_matrix(rows, cols, "X")
matrix2 = get_matrix(rows, cols, "Y")
while True:
# Menu for matrix operations
print("\nMatrix Operations Menu:")
print("1. Add matrices")
print("2. Subtract matrices")
print("3. Multiply matrices")
print("4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
result = add_matrices(matrix1, matrix2)
print("\nResult of matrix addition:")
print_matrix(result)
elif choice == 2:
result = subtract_matrices(matrix1, matrix2)
print("\nResult of matrix subtraction:")
print_matrix(result)
elif choice == 3:
if len(matrix1[0]) != len(matrix2):
print("Matrices cannot be multiplied. The number of columns in matrix 1
must equal the number of rows in matrix 2.")
else:
result = multiply_matrices(matrix1, matrix2)
print("\nResult of matrix multiplication:")
print_matrix(result)
elif choice == 4:
break
………………. ……………….

else:
print("Invalid choice. Please try again.")
if name == " main ":
main()

OUTPUT :
………………. ……………….

24.Program to find the sum of each row of the matrix.


SOURCE CODE :
def get_matrix_from_user():
n = int(input("Enter number of rows: "))
m = int(input("Enter number of columns: "))
matrix = []
for i in range(n):
row = []
for j in range(m):
row.append(int(input("Enter value for position (%d, %d): " %
(i+1, j+1)))) matrix.append(row)
return matrix
def print_matrix(matrix):
for row in matrix:
print(" ".join("%d" % x for x in row))
def calculate_row_sums(matrix):
for i, row in enumerate(matrix):
print("Sum of row %d: %d" % (i + 1, sum(row)))
def main():
matrix = get_matrix_from_user()
print_matrix(matrix)
calculate_row_sums(matrix)
if name == " main ":
main()
………………. ……………….

OUTPUT :
………………. ……………….

25.To find the largest and smallest element in each row.


SOURCE CODE :
def find_largest_smallest(matrix):
largest_smallest = [(max(row), min(row)) for row in matrix]
return largest_smallest
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
matrix = []
for i in range(rows):
row = []
for j in range(cols):
element = int(input("Enter element at position (%d, %d): " % (i + 1,
j + 1))) row.append(element)
matrix.append(row)
result = find_largest_smallest(matrix)
for i, (largest, smallest) in enumerate(result):
print("Largest in row %d: %d" % (i + 1, largest))
print("Smallest in row %d: %d" % (i + 1, smallest))

OUTPUT :
………………. ……………….

26.Write a program to compute mean, median, mode, standard deviation for


mark list of students1 subject.
SOURCE CODE :
def calculate_mean(marks):
return sum(marks) / len(marks)
def calculate_median(marks):
sorted_marks = sorted(marks)
n = len(marks)
if n % 2 == 0:
median = (sorted_marks[n//2 - 1] + sorted_marks[n//2]) / 2
else:
median = sorted_marks[n//2]
return median
def calculate_mode(marks):
mark_counts = {}
for mark in marks:
if mark in mark_counts:
mark_counts[mark] += 1
else:
mark_counts[mark] = 1
max_count = max(mark_counts.values())
modes = [mark for mark, count in mark_counts.items() if count == max_count]
if len(modes) == 1:
return modes[0]
else:
return "No unique mode"
def calculate_std_dev(marks):
mean = calculate_mean(marks)
variance = sum((x - mean) ** 2 for x in marks) / len(marks)
return variance ** 0.5
def calculate_stats():
n = int(input("Enter number of students: "))
………………. ……………….

marks = []
for i in range(n):
mark = float(input("Enter mark for student %d: " % (i + 1)))
marks.append(mark)
stats = {}
stats['mean'] = calculate_mean(marks)
stats['median'] = calculate_median(marks)
stats['mode'] = calculate_mode(marks)
stats['std_dev'] = calculate_std_dev(marks)
print("Mean: %.2f" % stats['mean'])
print("Median: %.2f" % stats['median'])
print("Mode: %s" % stats['mode'])
print("Standard Deviation: %.2f" % stats['std_dev'])
calculate_stats()

OUTPUT :
………………. ……………….

27.Write a program to create a dictionary to create the mark statement of n


students for 5 subjects and identify the topper in each subject.
SOURCE CODE :
def create_mark_statement(n):
mark_statement = {}
subjects = ["Math", "Science", "English", "History", "Geography"]
for i in range(1, n + 1):
student_marks = {}
for subject in subjects:
mark = int(input("Enter mark for %s for Student %d: " % (subject, i)))
student_marks[subject] = mark
mark_statement["Student %d" % i] = student_marks
return mark_statement
def identify_toppers(mark_statement):
toppers = {}
subjects = ["Math", "Science", "English", "History", "Geography"]
for subject in subjects:
max_mark = 0
topper = ""
for student, marks in mark_statement.items():
if marks[subject] > max_mark:
max_mark = marks[subject]
topper = student
toppers[subject] = topper
return toppers
n = int(input("Enter the number of students: "))
mark_statement = create_mark_statement(n)
print("\nMark Statement:")
for student, marks in mark_statement.items():
………………. ……………….

print("%s: %s" % (student, marks))


toppers = identify_toppers(mark_statement)
print("\nToppers in each subject:")
for subject, topper in toppers.items():
print("%s: %s" % (subject, topper))

OUTPUT :
………………. ……………….

28.Program for functions.


Write a program to accept the marks in 5 subjects for n students and identify
how many students have secured ( use multiple indexes and functions)
i. same mark in more than 3 subjects
ii. More than 80% in more than 2 subjects.
iii. Failed in 1 subject
iv. Failed in 2 subjects
SOURCE CODE :
def get_student_marks(n):
students = []
subjects = ["Math", "Science", "English", "History", "Geography"]
for i in range(1, n + 1):
student_marks = {}
for subject in subjects:
mark = int(input("Enter mark for %s for Student %d: " % (subject, i)))
student_marks[subject] = mark
students.append(student_marks)
return students
def same_mark_in_more_than_3_subjects(students):
count = 0
for student in students:
marks = list(student.values())
for mark in marks:
if marks.count(mark) > 3:
count += 1
break
return count
def more_than_80_percent_in_more_than_2_subjects(students):
count = 0
………………. ……………….

for student in students:


marks = list(student.values())
high_marks = [mark for mark in marks if mark > 80]
if len(high_marks) > 2:
count += 1
return count
def failed_in_1_subject(students):
count = 0
for student in students:
marks = list(student.values())
failed_marks = [mark for mark in marks if mark < 40]
if len(failed_marks) == 1:
count += 1
return count
def failed_in_2_subjects(students):
count = 0
for student in students:
marks = list(student.values())
failed_marks = [mark for mark in marks if mark < 40]
if len(failed_marks) == 2:
count += 1
return count
n = int(input("Enter the number of students: "))
students = get_student_marks(n)
print("Results:")
print("Students with same mark in more than 3 subjects: %d" %
same_mark_in_more_than_3_subjects(students))
print("Students with more than 80%% in more than 2 subjects: %d" %
more_than_80_percent_in_more_than_2_subjects(students))
print("Students who have failed in 1 subject: %d" % failed_in_1_subject(students))
………………. ……………….

print("Students who have failed in 2 subjects: %d" % failed_in_2_subjects(students))


print("Students who have failed in 2 subjects: {failed_in_2_subjects(students)}")

OUTPUT :
………………. ……………….

29.Program using Modules


SOURCE CODE :
# calc.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Cannot divide by zero!"
return a / b
# main.py (main program)
import calc
def main():
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = int(input("Enter your choice: "))
if choice == 1:
result = calc.add(num1, num2)
print("%f + %f = %f" % (num1, num2, result))
elif choice == 2:
result = calc.subtract(num1, num2)
print("%f - %f = %f" % (num1, num2, result))
………………. ……………….

elif choice == 3:
result = calc.multiply(num1, num2)
print("%f * %f = %f" % (num1, num2, result))
elif choice == 4:
result = calc.divide(num1, num2)
if result == "Cannot divide by zero!":
print(result)
else:
print("%f / %f = %f" % (num1, num2, result))
else:
print("Invalid choice")

if name == " main ":


main()

OUTPUT:
………………. ……………….

30.File implementation
SOURCE CODE :
def create_file(filename):
try:
file = open(filename, "w")
content = input("Enter the content to write to the file: ")
file.write(content)
file.close()
print("File %s created successfully." % filename)
except Exception as e:
print("Error creating file: %s" % str(e))
def read_file(filename):
try:
file = open(filename, "r")
content = file.read()
file.close()
print("File %s content: %s" % (filename, content))
except Exception as e:
print("Error reading file: %s" % str(e))
def append_file(filename):
try:
file = open(filename, "a")
content = input("Enter the content to append to the file: ")
file.write(content)
file.close()
print("File %s appended successfully." % filename)
except Exception as e:
print("Error appending file: %s" % str(e))
def delete_file(filename):
………………. ……………….

try:
import os
os.remove(filename)
print("File %s deleted successfully." % filename)
except Exception as e:
print("Error deleting file: %s" % str(e))
def main():
while True:
print("File Operations Menu:")
print("1. Create File")
print("2. Read File")
print("3. Append File")
print("4. Delete File")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == "1":
filename = input("Enter the filename: ")
create_file(filename)
elif choice == "2":
filename = input("Enter the filename: ")
read_file(filename)
elif choice == "3":
filename = input("Enter the filename: ")
append_file(filename)
elif choice == "4":
filename = input("Enter the filename: ")
delete_file(filename)
elif choice == "5":
print("Exiting program.")
break
………………. ……………….

else:
print("Invalid choice. Please try again.")
if name == " main ":
main()

OUTPUT :
………………. ……………….

31.Create a database (student or employee) in mysql/sqlite and perform the operations


of insertion, selection, updating through python cursor programs.
SOURCE CODE :
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="windows",
database="school"
)
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT,
grade VARCHAR(10)
)
''')
print("Table created successfully.")
def insert_student(name, age, grade):
cursor.execute('''
INSERT INTO students (name, age, grade) VALUES (%s, %s, %s)
''', (name, age, grade))
connection.commit()
print("Inserted: {name}, {age}, {grade}")
def fetch_students():
cursor.execute('SELECT * FROM students')
rows = cursor.fetchall()
if rows:
print("Students:")
for row in rows:
………………. ……………….

print(row)
else:
print("No students found.")
def update_student(student_id, name, age, grade):
cursor.execute('''
UPDATE students SET name = %s, age = %s, grade = %s WHERE id = %s
''', (name, age, grade, student_id))
connection.commit()
print("Updated student with ID {student_id}")
def main():
while True:
print("\nOptions:")
print("1. Insert Student")
print("2. Fetch Students")
print("3. Update Student")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
name = input("Enter student name: ")
age = int(input("Enter student age: "))
grade = input("Enter student grade: ")
insert_student(name, age, grade)
elif choice == '2':
fetch_students()
elif choice == '3':
student_id = int(input("Enter the ID of the student to update: "))
name = input("Enter new name: ")
age = int(input("Enter new age: "))
grade = input("Enter new grade: ")
update_student(student_id, name, age, grade)
elif choice == '4':
print("Exiting the program.")
break
………………. ……………….

else:
print("Invalid choice! Please enter a number between 1 and 4.")
main()
connection.close()
connection.close()

OUTPUT :
………………. ……………….

32.Create a static webpage for an organization (educational or business) with


image.

SOURCE CODE :

# views.py

from django.shortcuts import render


from django.http import HttpResponse

def welcome(request):
var = """
<html>
<head>
<title>SCMS COLLEGE</title>
<style>
#leftbox {float:left; background:white;width:50%;}
#rightbox {float:right;background:white;width:50%;}
#imagebox {text-align:center; width: 100%;}
h1, h2, h3 {color:black;text-align:center;}
</style>
</head>
<body>
<div id="imagebox">
<center>
<img
src="https://images.shiksha.com/mediadata/images/articles/1589894487phpkOmFSs.j
peg" alt="SCRS" width="60%" height="250">
</center>
………………. ……………….

</div>
<div id="leftbox">
<h3>ABOUT SSTM</h3>
<h2>SCMS School of Technology & Management</h2>
<p>SCMS School of Technology and Management (SSTM) is run as an institution
of excellence in management and technology education...</p>
</div>
<div id="rightbox">
<h3>VISION</h3>
<p>To be a socially committed centre of learning renowned for its excellence in
quality higher education & research...</p>
<h3>MISSION</h3>
<ul>
<li>To impart inclusive quality education to aspiring younger generation through
the best of teaching and learning opportunities.</li>
<li>To discover, nurture and enhance creativity and innovation...</li>
<li>To provide an enabling environment to inculcate human values...</li>
</ul>
</div>
</body>
</html>
"""
return HttpResponse(var)

# scms_website/settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
………………. ……………….

'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'scms_info', # Add your app here
]

# scms_website/urls.py

from django.contrib import admin


from django.urls import path
from scms_info.views import welcome

urlpatterns = [
path('admin/', admin.site.urls),
path('', welcome, name='welcome'),
]

OUTPUT :
………………. ……………….

33.Dynamic web page creation- project (document to be included: synopsis, executive


summary, normalized database tables, screen shots).

SOURCE CODE :
# Create your views here.
# views.py
from django.shortcuts import render, redirect, get_object_or_404
from stuapp.models import Student
def student_list(request):
if request.method == "POST":
# Create a new student
name = request.POST.get("name")
age = request.POST.get("age")
if name and age:
Student.objects.create(name=name, age=int(age))
return redirect('student_list')
students = Student.objects.all()
return render(request, 'student_list.html', {'students': students})
def delete_student(request, student_id):
student = get_object_or_404(Student, id=student_id)
student.delete()
return redirect('student_list')

# Create your models here.


# models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()

def __str__(self):
return self.name
………………. ……………….

# Create your urls here.


# urls.py

"""
URL configuration for stupro project.

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls import url
from stuapp import views

urlpatterns = [
url(r'^home/$', views.home, name='home'),
url(r'^about/$', views.about, name='about'),
]

settings.py

"""
Django settings for stupro project.
………………. ……………….

Generated by 'django-admin startproject' using Django 4.2.16.


For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production


# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-(c%ldd8-n8dm*)1h8o8g8#-
z&74i#ffr(ygd0vnz1mp$d41bpx'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'stuapp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
………………. ……………….

'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'stupro.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'stupro.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'elvindb',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
………………. ……………….

'PORT': '3306'
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME':
'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
………………. ……………….

STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

student_list.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Data Management</title>
<style>
body { font-family: Arial, sans-serif; background-color: #f4f4f9; color: #333; }
h1 { color: #2c3e50; }
form { margin-bottom: 20px; }
label { margin-right: 10px; }
ul { list-style: none; padding: 0; }
li { margin: 10px 0; }
button { background-color: #e74c3c; color: white; border: none; padding: 5px 10px;
cursor: pointer; }
button:hover { background-color: #c0392b; }
</style>
</head>
<body>
<h1>Student Data Management</h1>

<!-- Form to add a new student -->


<form method="POST">
{% csrf_token %}
<label for="name">Name:</label>
………………. ……………….

<input type="text" name="name" id="name" required>

<label for="age">Age:</label>
<input type="number" name="age" id="age" required>

<button type="submit">Add Student</button>


</form>

<h2>Student List:</h2>
<ul>
{% for student in students %}
<li>
<strong>{{ student.name }}</strong>, Age: {{ student.age }}
<!-- Delete button for each student -->
<form action="{% url 'delete_student' student.id %}" method="post"
style="display:inline;">
{% csrf_token %}
<button type="submit">Delete</button>
</form>
</li>
{% empty %}
<li>No students available.</li>
{% endfor %}
</ul>
</body>
</html>
………………. ……………….

OUTPUT:
………………. ……………….

34.Write a NumPy program to remove all rows in a NumPy array that contain non
numeric values
SOURCE CODE :
import numpy as np
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
arr = []
print("\nEnter elements for each row:")
for i in range(rows):
row = input("Row {i + 1}: ").split() # Split input into list of strings
arr.append(row)
arr = np.array(arr)
numeric_rows = [row for row in arr if all(cell.isnumeric() for cell in row)]
filtered_arr = np.array(numeric_rows)
print("\nFiltered Array:")
print(filtered_arr)
OUTPUT :
………………. ……………….

35.Write a program to perform the following in n*m Matrices.Addition,Subtraction,


Difference, Division,Transpose
SOURCE CODE :
import numpy as np
def matrix_operations(matrix1, matrix2):
results = {}
results['addition'] = np.add(matrix1, matrix2)
results['subtraction'] = np.subtract(matrix1, matrix2)
results['dot_product'] = np.dot(matrix1, matrix2) # Changed to dot product
results['division'] = np.divide(matrix1, matrix2)
results['transpose_matrix1'] = np.transpose(matrix1)
results['transpose_matrix2'] = np.transpose(matrix2)
return results
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
print("\nEnter elements for the first matrix:")
matrix1 = []
for _ in range(rows):
row = input().split()
int_row = [int(x) for x in row]
matrix1.append(int_row)
matrix1 = np.array(matrix1)
print("\nEnter elements for the second matrix:")
matrix2 = []
for _ in range(rows):
row = input().split()
int_row = [int(x) for x in row]
matrix2.append(int_row)
matrix2 = np.array(matrix2)
results = matrix_operations(matrix1, matrix2)
for operation, result in results.items():
print("\n{operation.capitalize()}:")
print(result)
………………. ……………….

OUTPUT :
………………. ……………….

36.Write a NumPy program (using NumPy) to sum of all the multiples of 3 or 5 below
100.
SOURCE CODE :
import numpy as np
n = int(input("Enter the upper limit: "))
numbers = np.arange(1, n)
multiples = numbers[(numbers % 3 == 0) | (numbers % 5 == 0)]
total_sum = np.sum(multiples)
print("Sum of multiples of 3 or 5 below", n, ":", total_sum)

OUTPUT :
………………. ……………….

37.Write a Pandas program to drop the columns where at least one element is missing
in a given DataFrame.
SOURCE CODE :
import pandas as pd
import numpy as npr
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
data = {}
for j in range(cols):
col_name = input(f"Enter column name {j + 1}: ")
col_data = []
for i in range(rows):
value = input(f"Enter value for row {i + 1}, column '{col_name}': ")
if value == "":
col_data.append(np.nan)
else:
try:
col_data.append(int(value))
except ValueError:
col_data.append(value)
data[col_name] = col_data
df = pd.DataFrame(data)
df_dropped = df.dropna(axis=1)
print("\nOriginal DataFrame:")
print(df)
print("\nDataFrame after dropping columns with missing values:")
print(df_dropped)
………………. ……………….

OUTPUT :
………………. ……………….

38.Write a Pandas program to find and replace the missing values with mean in a given
Data Frame.
SOURCE CODE :
import pandas as pd
import numpy as np
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
data = []
for i in range(rows):
row_data = input(f"Enter elements for row {i + 1} (use 'nan' for missing values, separated
by spaces): ").split()
row_data = [float(x) if x != 'nan' else np.nan for x in row_data]
data.append(row_data)
df = pd.DataFrame(data)
for col in df.columns:
if df[col].isnull().any():
col_mean = df[col].mean()
df[col].fillna(col_mean, inplace=True)
print("\nDataFrame after imputation:")
print(df)
OUTPUT :
………………. ……………….

40.Create Different Subplot Sizes in Matplotlib with legend and titles.


SOURCE CODE :
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [3, 6, 9, 12, 15]
fig, axs = plt.subplots(2, 2, figsize=(8, 6))
axs[0, 0].plot(x, y1, label='Plot 1')
axs[0, 1].plot(x, y2, label='Plot 2')
axs[1, 0].plot(x, y1, label='Plot 3')
axs[1, 1].plot(x, y2, label='Plot 4')
for ax in axs.flat:
ax.legend()
ax.set_title('Subplot')
plt.tight_layout()
plt.show()
OUTPUT :
………………. ……………….

42.Implementation of at least one classification algorithm using Scikit-learn


SOURCE CODE :
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
num_samples = int(input("Enter the number of samples: "))
num_features = int(input("Enter the number of features: "))
X = []
print("\nEnter features for each sample (space-separated):")
for i in range(num_samples):
features = input(f"Sample {i + 1}: ").split()
X.append([float(x) for x in features])
print("\nEnter target variable values (space-separated, 0 or 1):")
y = [int(x) for x in input().split()]
X = np.array(X)
y = np.array(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
OUTPUT :
………………. ……………….

43.Implementation of at least one clustering algorithm using Scikit-learn


SOURCE CODE :
import numpy as np
from sklearn.cluster import KMeans
num_points = int(input("Enter the number of data points: "))
num_features = int(input("Enter the number of features for each point: "))
data_points = []
print("\nEnter features for each data point (space-separated):")
for i in range(num_points):
features = input(f"Point {i + 1}: ").split()
data_points.append([float(x) for x in features])
num_clusters = int(input("\nEnter the number of clusters: "))
X = np.array(data_points)
kmeans = KMeans(n_clusters=num_clusters)
kmeans.fit(X)
print("Cluster Labels:", kmeans.labels_)
print("Cluster Centers:\n", kmeans.cluster_centers_)

OUTPUT :
………………. ……………….
………………. ……………….

You might also like