PYTHON programs
PYTHON programs
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))
reversed_num = reverse_number(num)
sum_of_digits_num = sum_of_digits(num)
OUTPUT :
………………. ……………….
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 :
………………. ……………….
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 :
………………. ……………….
OUTPUT :
………………. ……………….
OUTPUT :
………………. ……………….
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 :
………………. ……………….
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 :
………………. ……………….
OUTPUT :
………………. ……………….
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 :
………………. ……………….
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 :
………………. ……………….
else:
print("Invalid choice. Please try again.")
if name == " main ":
main()
OUTPUT :
………………. ……………….
OUTPUT :
………………. ……………….
OUTPUT :
………………. ……………….
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 :
………………. ……………….
OUTPUT :
………………. ……………….
OUTPUT :
………………. ……………….
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")
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 :
………………. ……………….
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 :
………………. ……………….
SOURCE CODE :
# views.py
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
urlpatterns = [
path('admin/', admin.site.urls),
path('', welcome, name='welcome'),
]
OUTPUT :
………………. ……………….
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')
def __str__(self):
return self.name
………………. ……………….
"""
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.
………………. ……………….
'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>
<label for="age">Age:</label>
<input type="number" name="age" id="age" required>
<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 :
………………. ……………….
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 :
………………. ……………….
OUTPUT :
………………. ……………….
………………. ……………….