0% found this document useful (0 votes)
12 views46 pages

Python Projects for Class 12 Students

The document outlines a Python programming project for 12th-grade students at Silver Shine School, detailing various programming tasks and examples. It includes a comprehensive index of 86 programming exercises covering topics such as number classification, string manipulation, list operations, file handling, and database interactions. Each program is accompanied by sample code and expected output.

Uploaded by

rafiwap630
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)
12 views46 pages

Python Projects for Class 12 Students

The document outlines a Python programming project for 12th-grade students at Silver Shine School, detailing various programming tasks and examples. It includes a comprehensive index of 86 programming exercises covering topics such as number classification, string manipulation, list operations, file handling, and database interactions. Each program is accompanied by sample code and expected output.

Uploaded by

rafiwap630
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

SILVER SHINE SCHOOL

Python Programming
Project

Computer Science (083)


Session: 2023-24

Submitted By: Amrit Srivastav

Class: 12th

Section: A

Roll No: 04
INDEX

1. Check if a number is positive, negative, or zero

2. Check if a number is prime

3. Find factorial of a number using loop

4. Print Fibonacci series up to n terms

5. Reverse a number

6. Check if a number is palindrome

7. Check if a string is palindrome

8. Calculate sum of digits of a number

9. Check if a year is a leap year

10. Count vowels and consonants in a string

11. Reverse a string using slicing

12. Swap two numbers without using a third variable

13. Find length of a string without using len()

14. Check if a character is vowel or consonant

15. Count number of words in a sentence

16. Find maximum and minimum in a list

17. Count even and odd numbers in a list

18. Find sum of all elements in a list

19. Find second largest number in a list

20. Check whether an element exists in a list

21. Remove all duplicates from a list

22. Find common elements between two lists

23. Create a list and perform append, insert, remove, pop


24. Create a tuple and access its elements

25. Create a dictionary and perform CRUD operations

26. Count frequency of each character in a string

27. Check if a number is an Armstrong number

28. Print all prime numbers between two intervals

29. Convert Celsius to Fahrenheit

30. Convert decimal to binary, octal, and hexadecimal

31. Find LCM of two numbers

32. Calculate power of a number without using **

33. Print a star triangle pattern

34. Print number pattern (1, 22, 333…)

35. Capitalize first letter of every word

36. Create a simple calculator using if-elif

37. Print ASCII value of a character

38. Print uppercase and lowercase letters separately

39. Count digits, letters, spaces, and special character

40. Create a text file and write student details

41. Read text file line by line

42. Count lines, words, and characters in a text file

43. Display lines starting with a vowel

44. Count frequency of a specific word

45. Copy contents from one text file to another

46. Remove blank lines from a text file

47. Display lines containing the word "Python"

48. Count uppercase and lowercase characters in a file


49. Display only even-numbered lines from a file

50. Create a binary file to store student records

51. Display all records from a binary file

52. Search student record by roll number

53. Update marks of a student

54. Delete a student record

55. Count total records in binary file

56. Display students scoring more than 75 marks

57. Append new records to binary file

58. Display binary records in formatted form

59. Copy records from one binary file to another

60. Create CSV file and write student records

61. Read and display CSV records

62. Append new records to CSV file

63. Display CSV records in tabular format

64. Search student by roll number

65. Display students from a specific city

66. Search students whose names start with a given letter

67. Update marks in CSV file

68. Count total records in CSV file

69. Create database School

70. Select database School

71. Create STUDENT table with proper data types

72. Display structure of STUDENT table

73. Insert one record into STUDENT table


74. Insert multiple records into STUDENT table

75. Display all records from STUDENT table

76. Display name and marks only

77. Display students of Class 12

78. Display students scoring more than 80 marks

79. Display students belonging to Delhi

80. Display students with marks between 70 and 90

81. Display students whose names start with 'A'

82. Update marks using RollNo

83. Connect Python with MySQL

84. Insert records using parameterized queries

85. Search, update, and delete records via Python

86. Menu-driven program for Student / Employee Database


Program 1: Check if a number is positive, negative, or zero

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


if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Output:
Enter a number: -5
Negative number

Program 2: Check if a number is prime

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


if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

Output:
Enter a number: 11
11 is a prime number
Program 3: Find factorial of a number using loop

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


factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial = factorial * i
print("The factorial of", num, "is", factorial)

Output:
Enter a number: 5
The factorial of 5 is 120

Program 4: Print Fibonacci series up to n terms

nterms = int(input("How many terms? "))


n1, n2 = 0, 1
count = 0

if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto", nterms, ":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1

Output:
How many terms? 5
Fibonacci sequence:
0
1
1
2
3
Program 5: Reverse a number

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


reversed_num = 0

while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10

print("Reversed Number: " + str(reversed_num))

Output:
Enter a number: 1234
Reversed Number: 4321

Program 6: Check if a number is palindrome

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


temp = num
rev = 0
while temp > 0:
dig = temp % 10
rev = rev * 10 + dig
temp = temp // 10
if num == rev:
print("The number is a palindrome")
else:
print("The number is not a palindrome")

Output:
Enter a number: 121
The number is a palindrome
Program 7: Check if a string is palindrome

my_str = input("Enter a string: ")


my_str = my_str.casefold()
rev_str = reversed(my_str)

if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

Output:
Enter a string: Madam
The string is a palindrome.

Program 8: Calculate sum of digits of a number

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


tot = 0
while n > 0:
dig = n % 10
tot = tot + dig
n = n // 10
print("The total sum of digits is:", tot)

Output:
Enter a number: 456
The total sum of digits is: 15
Program 9: Check if a year is a leap year

year = int(input("Enter a year: "))


if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))
elif (year % 4 == 0) and (year % 100 != 0):
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))

Output:
Enter a year: 2024
2024 is a leap year

Program 10: Count vowels and consonants in a string

str1 = input("Please Enter Your String : ")


vowels = 0
consonants = 0
str1 = [Link]()

for i in str1:
if(i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u'):
vowels = vowels + 1
elif((i >= 'a' and i <= 'z')):
consonants = consonants + 1

print("Total Number of Vowels in this String = ", vowels)


print("Total Number of Consonants in this String = ", consonants)

Output:
Please Enter Your String : Python
Total Number of Vowels in this String = 1
Total Number of Consonants in this String = 5

Program 11: Reverse a string using slicing

txt = input("Enter a string: ")


reversed_txt = txt[::-1]
print("Reversed String:", reversed_txt)

Output:
Enter a string: Hello
Reversed String: olleH
Program 12: Swap two numbers without using a third variable

x = 5
y = 10
print("Before swapping: x =", x, " y =", y)
x, y = y, x
print("After swapping: x =", x, " y =", y)

Output:
Before swapping: x = 5 y = 10
After swapping: x = 10 y = 5
Program 13: Find length of a string without using len()

string = input("Enter a string: ")


count = 0
for s in string:
count = count + 1
print("Length of the string is:", count)

Output:
Enter a string: Computer
Length of the string is: 8

Program 14: Check if a character is vowel or consonant

ch = input("Enter a character: ")


if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I'
or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant")

Output:
Enter a character: e
e is a Vowel

Program 15: Count number of words in a sentence

test_string = "Silver Shine School Project"


print("The original string is: " + test_string)
res = len(test_string.split())
print("The number of words in string are: " + str(res))

Output:
The original string is: Silver Shine School Project
The number of words in string are: 4
Program 16: Find maximum and minimum in a list

numbers = [12, 45, 2, 9, 60, 34]


print("List:", numbers)
print("Maximum number:", max(numbers))
print("Minimum number:", min(numbers))

Output:
List: [12, 45, 2, 9, 60, 34]
Maximum number: 60
Minimum number: 2
Program 17: Count even and odd numbers in a list

list1 = [10, 21, 4, 45, 66, 93]


even_count, odd_count = 0, 0

for num in list1:


if num % 2 == 0:
even_count += 1
else:
odd_count += 1

print("Even numbers in the list:", even_count)


print("Odd numbers in the list:", odd_count)

Output:
Even numbers in the list: 3
Odd numbers in the list: 3

Program 18: Find sum of all elements in a list

numbers = [1, 2, 3, 4, 5]
total_sum = 0
for n in numbers:
total_sum += n
print("Sum of elements:", total_sum)

Output:
Sum of elements: 15

Program 19: Find second largest number in a list

list1 = [10, 20, 4, 45, 99]


[Link]()
print("Second largest element is:", list1[-2])

Output:
Second largest element is: 45
Program 20: Check whether an element exists in a list

test_list = [1, 6, 3, 5, 3, 4]
i = 3
if i in test_list:
print("Element exists")
else:
print("Element does not exist")

Output:
Element exists

Program 21: Remove all duplicates from a list

my_list = [1, 2, 2, 3, 4, 4, 5]
my_list = list([Link](my_list))
print(my_list)

Output:
[1, 2, 3, 4, 5]
Program 22: Find common elements between two lists

a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
common = list(set(a) & set(b))
print("Common elements:", common)

Output:
Common elements: [5]

Program 23: Create a list and perform append, insert, remove, pop

lst = [10, 20, 30]


[Link](40)
print("After Append:", lst)
[Link](1, 15)
print("After Insert:", lst)
[Link](20)
print("After Remove 20:", lst)
[Link]()
print("After Pop:", lst)

Output:
After Append: [10, 20, 30, 40]
After Insert: [10, 15, 20, 30, 40]
After Remove 20: [10, 15, 30, 40]
After Pop: [10, 15, 30]

Program 24: Create a tuple and access its elements

my_tuple = ("apple", "banana", "cherry")


print(my_tuple)
print("Second element:", my_tuple[1])

Output:
("apple", "banana", "cherry")
Second element: banana
Program 25: Create a dictionary and perform CRUD operations

student = {'Name': 'Amrit', 'Age': 17}


print("Original:", student)

# Create/Update
student['Class'] = '12th'
print("After adding Class:", student)

# Read
print("Name is:", student['Name'])

# Delete
del student['Age']
print("After deleting Age:", student)

Output:
Original: {'Name': 'Amrit', 'Age': 17}
After adding Class: {'Name': 'Amrit', 'Age': 17, 'Class': '12th'}
Name is: Amrit
After deleting Age: {'Name': 'Amrit', 'Class': '12th'}
Program 26: Count frequency of each character in a string

test_str = "hello"
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
print("Count of all characters in hello is :\n " + str(all_freq))

Output:
Count of all characters in hello is :
{'h': 1, 'e': 1, 'l': 2, 'o': 1}

Program 27: Check if a number is an Armstrong number

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


sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")

Output:
Enter a number: 153
153 is an Armstrong number
Program 28: Print all prime numbers between two intervals

lower = 10
upper = 20
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

Output:
Prime numbers between 10 and 20 are:
11
13
17
19

Program 29: Convert Celsius to Fahrenheit

celsius = 37.5
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' % (celsius,
fahrenheit))

Output:
37.5 degree Celsius is equal to 99.5 degree Fahrenheit
Program 30: Convert decimal to binary, octal, and hexadecimal

dec = 344
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary")
print(oct(dec), "in octal")
print(hex(dec), "in hexadecimal")

Output:
The decimal value of 344 is:
0b101011000 in binary
0o530 in octal
0x158 in hexadecimal

Program 31: Find LCM of two numbers

def compute_lcm(x, y):


if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm

print("The LCM is", compute_lcm(54, 24))

Output:
The LCM is 216

Program 32: Calculate power of a number without using **

base = 3
exponent = 4
result = 1
while exponent != 0:
result *= base
exponent -= 1
print("Result:", result)

Output:
Result: 81
Program 33: Print a star triangle pattern

n = 5
for i in range(0, n):
for j in range(0, i + 1):
print("*", end=" ")
print()

Output:
*
* *
* * *
* * * *
* * * * *
Program 34: Print number pattern (1, 22, 333…)

n = 5
for i in range(1, n+1):
for j in range(1, i+1):
print(i, end="")
print()

Output:
1
22
333
4444
55555

Program 35: Capitalize first letter of every word

s = "silver shine school"


print([Link]())

Output:
Silver Shine School

Program 36: Create a simple calculator using if-elif

def calculator(a, b, op):


if op == '+': return a + b
elif op == '-': return a - b
elif op == '*': return a * b
elif op == '/': return a / b
else: return "Invalid"

print("10 + 5 =", calculator(10, 5, '+'))


print("10 * 5 =", calculator(10, 5, '*'))

Output:
10 + 5 = 15
10 * 5 = 50
Program 37: Print ASCII value of a character

c = 'p'
print("The ASCII value of '" + c + "' is", ord(c))

Output:
The ASCII value of 'p' is 112

Program 38: Print uppercase and lowercase letters separately

text = "SilverShine"
upper = ""
lower = ""
for char in text:
if [Link]():
upper += char
elif [Link]():
lower += char
print("Uppercase:", upper)
print("Lowercase:", lower)

Output:
Uppercase: SS
Lowercase: ilverhine
Program 39: Count digits, letters, spaces, and special character

s = "Class 12 @ 2024"
d=l=sp=spl=0
for c in s:
if [Link](): d=d+1
elif [Link](): l=l+1
elif [Link](): sp=sp+1
else: spl=spl+1
print("Digits:", d, "Letters:", l, "Spaces:", sp, "Special:", spl)

Output:
Digits: 6 Letters: 5 Spaces: 3 Special: 1

Program 40: Create a text file and write student details

f = open("[Link]", "w")
[Link]("Amrit\n")
[Link]("Class 12\n")
[Link]("Roll No 04\n")
[Link]()
print("File created successfully.")

Output:
File created successfully.

Program 41: Read text file line by line

f = open("[Link]", "r")
for line in f:
print([Link]())
[Link]()

Output:
Amrit
Class 12
Roll No 04
Program 42: Count lines, words, and characters in a text file

f = open("[Link]", "r")
lines = 0
words = 0
chars = 0
for line in f:
lines += 1
words += len([Link]())
chars += len(line)
[Link]()
print("Lines:", lines, "Words:", words, "Chars:", chars)

Output:
Lines: 3 Words: 6 Chars: 26
Program 43: Display lines starting with a vowel

# Assuming file contains:


# Apple
# Banana
# Orange
f = open("[Link]", "r")
for line in f:
if line[0].lower() in 'aeiou':
print([Link]())
[Link]()

Output:
Apple
Orange

Program 44: Count frequency of a specific word

word_to_find = "Python"
count = 0
with open("[Link]", "r") as f:
for line in f:
words = [Link]()
for i in words:
if i == word_to_find:
count += 1
print("Occurrences of 'Python':", count)

Output:
Occurrences of 'Python': 3

Program 45: Copy contents from one text file to another

with open("[Link]", "r") as f1:


with open("[Link]", "w") as f2:
for line in f1:
[Link](line)
print("File copied.")

Output:
File copied.
Program 46: Remove blank lines from a text file

with open("[Link]", "r") as f:


lines = [Link]()
with open("[Link]", "w") as f:
for line in lines:
if [Link]():
[Link](line)
print("Blank lines removed.")

Output:
Blank lines removed.

Program 47: Display lines containing the word "Python"

with open("[Link]", "r") as f:


for line in f:
if "Python" in line:
print([Link]())

Output:
Python is fun
We love Python programming
Program 48: Count uppercase and lowercase characters in a file

upper = 0
lower = 0
with open("[Link]", "r") as f:
data = [Link]()
for char in data:
if [Link]():
upper += 1
elif [Link]():
lower += 1
print("Upper:", upper, "Lower:", lower)

Output:
Upper: 15 Lower: 85

Program 49: Display only even-numbered lines from a file

with open("[Link]", "r") as f:


lines = [Link]()
for i in range(1, len(lines), 2):
print(lines[i].strip())

Output:
Line 2 content
Line 4 content

Program 50: Create a binary file to store student records

import pickle
records = [[1, "Amrit", 95], [2, "Rahul", 88], [3, "Priya", 92]]
with open("[Link]", "wb") as f:
[Link](records, f)
print("Binary file created.")

Output:
Binary file created.
Program 51: Display all records from a binary file

import pickle
with open("[Link]", "rb") as f:
data = [Link](f)
for row in data:
print(row)

Output:
[1, 'Amrit', 95]
[2, 'Rahul', 88]
[3, 'Priya', 92]

Program 52: Search student record by roll number

import pickle
roll = 2
found = False
with open("[Link]", "rb") as f:
data = [Link](f)
for row in data:
if row[0] == roll:
print("Found:", row)
found = True
if not found: print("Not found")

Output:
Found: [2, 'Rahul', 88]
Program 53: Update marks of a student

import pickle
roll = 2
new_marks = 90
with open("[Link]", "rb") as f:
data = [Link](f)

for row in data:


if row[0] == roll:
row[2] = new_marks

with open("[Link]", "wb") as f:


[Link](data, f)
print("Marks updated.")

Output:
Marks updated.

Program 54: Delete a student record

import pickle
roll_to_delete = 3
with open("[Link]", "rb") as f:
data = [Link](f)

new_data = [row for row in data if row[0] != roll_to_delete]

with open("[Link]", "wb") as f:


[Link](new_data, f)
print("Record deleted.")

Output:
Record deleted.

Program 55: Count total records in binary file

import pickle
with open("[Link]", "rb") as f:
data = [Link](f)
print("Total records:", len(data))

Output:
Total records: 2
Program 56: Display students scoring more than 75 marks

import pickle
with open("[Link]", "rb") as f:
data = [Link](f)
for row in data:
if row[2] > 75:
print(row)

Output:
[1, 'Amrit', 95]
[2, 'Rahul', 90]

Program 57: Append new records to binary file

import pickle
new_rec = [4, "Sneha", 85]
with open("[Link]", "rb") as f:
data = [Link](f)
[Link](new_rec)
with open("[Link]", "wb") as f:
[Link](data, f)
print("Record appended.")

Output:
Record appended.
Program 58: Display binary records in formatted form

import pickle
print(f"{'Roll':<10}{'Name':<15}{'Marks':<10}")
print("-" * 35)
with open("[Link]", "rb") as f:
data = [Link](f)
for row in data:
print(f"{row[0]:<10}{row[1]:<15}{row[2]:<10}")

Output:
Roll Name Marks
-----------------------------------
1 Amrit 95
2 Rahul 90
4 Sneha 85

Program 59: Copy records from one binary file to another

import pickle
with open("[Link]", "rb") as f1:
data = [Link](f1)
with open("[Link]", "wb") as f2:
[Link](data, f2)
print("Backup created.")

Output:
Backup created.

Program 60: Create CSV file and write student records

import csv
data = [["Roll", "Name", "City"],
[1, "Amrit", "Delhi"],
[2, "Rahul", "Mumbai"]]
with open("[Link]", "w", newline='') as f:
writer = [Link](f)
[Link](data)
print("CSV file created.")

Output:
CSV file created.
Program 61: Read and display CSV records

import csv
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(row)

Output:
['Roll', 'Name', 'City']
['1', 'Amrit', 'Delhi']
['2', 'Rahul', 'Mumbai']

Program 62: Append new records to CSV file

import csv
with open("[Link]", "a", newline='') as f:
writer = [Link](f)
[Link]([3, "Priya", "Pune"])
print("Record appended to CSV.")

Output:
Record appended to CSV.
Program 63: Display CSV records in tabular format

import csv
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(f"{row[0]:<10} {row[1]:<15} {row[2]:<10}")

Output:
Roll Name City
1 Amrit Delhi
2 Rahul Mumbai
3 Priya Pune

Program 64: Search student by roll number

import csv
roll = '2'
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
if row[0] == roll:
print("Found:", row)

Output:
Found: ['2', 'Rahul', 'Mumbai']

Program 65: Display students from a specific city

import csv
city = "Delhi"
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
if len(row) > 2 and row[2] == city:
print(row)

Output:
['1', 'Amrit', 'Delhi']
Program 66: Search students whose names start with a given letter

import csv
char = 'A'
with open("[Link]", "r") as f:
reader = [Link](f)
next(reader) # skip header
for row in reader:
if row[1].startswith(char):
print(row)

Output:
['1', 'Amrit', 'Delhi']

Program 67: Update marks in CSV file

# Assuming file has Roll, Name, Marks


import csv
records = []
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
if row[0] == '1': # Roll 1
row[2] = '99' # Update Marks
[Link](row)

with open("[Link]", "w", newline='') as f:


writer = [Link](f)
[Link](records)
print("Updated successfully")

Output:
Updated successfully
Program 68: Count total records in CSV file

import csv
with open("[Link]", "r") as f:
reader = [Link](f)
count = sum(1 for row in reader) - 1 # exclude header
print("Total records:", count)

Output:
Total records: 3

Program 69: Create database School

import [Link]
mydb =
[Link](host="localhost",user="root",passwd="password")
mycursor = [Link]()
[Link]("CREATE DATABASE School")
print("Database created")

Output:
Database created

Program 70: Select database School

import [Link]
mydb = [Link](host="localhost",user="root",
passwd="password",database="School")
print("Connected to School database")

Output:
Connected to School database
Program 71: Create STUDENT table with proper data types

mycursor = [Link]()
[Link]("CREATE TABLE STUDENT (RollNo INT, Name VARCHAR(255), Marks
INT)")
print("Table created")

Output:
Table created

Program 72: Display structure of STUDENT table

[Link]("DESCRIBE STUDENT")
for x in mycursor:
print(x)

Output:
('RollNo', 'int(11)', 'YES', '', None, '')
('Name', 'varchar(255)', 'YES', '', None, '')
('Marks', 'int(11)', 'YES', '', None, '')
Program 73: Insert one record into STUDENT table

sql = "INSERT INTO STUDENT (RollNo, Name, Marks) VALUES (1, 'Amrit', 95)"
[Link](sql)
[Link]()
print([Link], "record inserted.")

Output:
1 record inserted.

Program 74: Insert multiple records into STUDENT table

sql = "INSERT INTO STUDENT (RollNo, Name, Marks) VALUES (%s, %s, %s)"
val = [
(2, "Rahul", 85),
(3, "Sneha", 92),
(4, "Priya", 78)
]
[Link](sql, val)
[Link]()
print([Link], "records inserted.")

Output:
3 records inserted.

Program 75: Display all records from STUDENT table

[Link]("SELECT * FROM STUDENT")


myresult = [Link]()
for x in myresult:
print(x)

Output:
(1, 'Amrit', 95)
(2, 'Rahul', 85)
(3, 'Sneha', 92)
(4, 'Priya', 78)
Program 76: Display name and marks only

[Link]("SELECT Name, Marks FROM STUDENT")


myresult = [Link]()
for x in myresult:
print(x)

Output:
('Amrit', 95)
('Rahul', 85)
('Sneha', 92)
('Priya', 78)

Program 77: Display students of Class 12

# Assuming table has Class column


sql = "SELECT * FROM STUDENT WHERE Class = '12'"
[Link](sql)
myresult = [Link]()
for x in myresult:
print(x)

Output:
(1, 'Amrit', 95, '12')
Program 78: Display students scoring more than 80 marks

sql = "SELECT * FROM STUDENT WHERE Marks > 80"


[Link](sql)
myresult = [Link]()
for x in myresult:
print(x)

Output:
(1, 'Amrit', 95)
(2, 'Rahul', 85)
(3, 'Sneha', 92)

Program 79: Display students belonging to Delhi

# Assuming table has City column


sql = "SELECT * FROM STUDENT WHERE City = 'Delhi'"
[Link](sql)
myresult = [Link]()
for x in myresult:
print(x)

Output:
(1, 'Amrit', 95, 'Delhi')

Program 80: Display students with marks between 70 and 90

sql = "SELECT * FROM STUDENT WHERE Marks BETWEEN 70 AND 90"


[Link](sql)
myresult = [Link]()
for x in myresult:
print(x)

Output:
(2, 'Rahul', 85)
(4, 'Priya', 78)
Program 81: Display students whose names start with 'A'

sql = "SELECT * FROM STUDENT WHERE Name LIKE 'A%'"


[Link](sql)
myresult = [Link]()
for x in myresult:
print(x)

Output:
(1, 'Amrit', 95)

Program 82: Update marks using RollNo

sql = "UPDATE STUDENT SET Marks = 98 WHERE RollNo = 1"


[Link](sql)
[Link]()
print([Link], "record(s) updated")

Output:
1 record(s) updated
Program 83: Connect Python with MySQL

import [Link]

try:
mydb = [Link](
host="localhost",
user="root",
password="password",
database="School"
)
if mydb.is_connected():
print("Successfully connected to MySQL database")
mycursor = [Link]()
[Link]("SELECT DATABASE();")
record = [Link]()
print("You're connected to database:", record)
except Exception as e:
print("Error while connecting to MySQL", e)
finally:
if mydb.is_connected():
[Link]()
[Link]()
print("MySQL connection is closed")

Output:
Successfully connected to MySQL database
You're connected to database: ('School',)
MySQL connection is closed
Program 84: Insert records using parameterized queries

import [Link]

mydb = [Link](
host="localhost",
user="root",
password="password",
database="School"
)
mycursor = [Link]()

# Parameterized query to prevent SQL injection


sql = "INSERT INTO STUDENT (RollNo, Name, Marks) VALUES (%s, %s, %s)"

# Taking input from user


roll = int(input("Enter Roll No: "))
name = input("Enter Name: ")
marks = int(input("Enter Marks: "))

val = (roll, name, marks)


[Link](sql, val)
[Link]()

print([Link], "record inserted using parameterized query")

Output:
Enter Roll No: 5
Enter Name: Rohan
Enter Marks: 88
1 record inserted using parameterized query
Program 85: Search, update, and delete records via Python

import [Link]

mydb = [Link](
host="localhost",
user="root",
password="password",
database="School"
)
mycursor = [Link]()

# Search
print("--- SEARCH RECORD ---")
roll = int(input("Enter Roll No to search: "))
sql = "SELECT * FROM STUDENT WHERE RollNo = %s"
[Link](sql, (roll,))
result = [Link]()
if result:
print("Record found:", result)
else:
print("Record not found")

# Update
print("\n--- UPDATE RECORD ---")
roll = int(input("Enter Roll No to update: "))
new_marks = int(input("Enter new Marks: "))
sql = "UPDATE STUDENT SET Marks = %s WHERE RollNo = %s"
[Link](sql, (new_marks, roll))
[Link]()
print([Link], "record(s) updated")

# Delete
print("\n--- DELETE RECORD ---")
roll = int(input("Enter Roll No to delete: "))
sql = "DELETE FROM STUDENT WHERE RollNo = %s"
[Link](sql, (roll,))
[Link]()
print([Link], "record(s) deleted")

Output:
--- SEARCH RECORD ---
Enter Roll No to search: 2
Record found: (2, 'Rahul', 85)

--- UPDATE RECORD ---


Enter Roll No to update: 2
Enter new Marks: 90
1 record(s) updated

--- DELETE RECORD ---


Enter Roll No to delete: 4
1 record(s) deleted
Program 86: Menu-driven program for Student / Employee Database

import [Link]

mydb = [Link](
host="localhost",
user="root",
password="password",
database="School"
)
mycursor = [Link]()

while True:
print("\n===== STUDENT DATABASE MANAGEMENT =====")
print("1. Add New Student")
print("2. Display All Students")
print("3. Search Student by Roll No")
print("4. Update Student Marks")
print("5. Delete Student")
print("6. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
roll = int(input("Enter Roll No: "))
name = input("Enter Name: ")
marks = int(input("Enter Marks: "))
sql = "INSERT INTO STUDENT VALUES (%s, %s, %s)"
[Link](sql, (roll, name, marks))
[Link]()
print("Student added successfully!")

elif choice == 2:
[Link]("SELECT * FROM STUDENT")
result = [Link]()
print("\nRoll\tName\tMarks")
print("-" * 30)
for row in result:
print(f"{row[0]}\t{row[1]}\t{row[2]}")

elif choice == 3:
roll = int(input("Enter Roll No: "))
sql = "SELECT * FROM STUDENT WHERE RollNo = %s"
[Link](sql, (roll,))
result = [Link]()
if result:
print("Roll:", result[0], "Name:", result[1], "Marks:",
result[2])
else:
print("Student not found!")

elif choice == 4:
roll = int(input("Enter Roll No: "))
marks = int(input("Enter new Marks: "))
sql = "UPDATE STUDENT SET Marks = %s WHERE RollNo = %s"
[Link](sql, (marks, roll))
[Link]()
print("Marks updated successfully!")

elif choice == 5:
roll = int(input("Enter Roll No: "))
sql = "DELETE FROM STUDENT WHERE RollNo = %s"
[Link](sql, (roll,))
[Link]()
print("Student deleted successfully!")

elif choice == 6:
print("Exiting program...")
break
else:
print("Invalid choice!")
[Link]()
[Link]()

Output:
===== STUDENT DATABASE MANAGEMENT =====
1. Add New Student
2. Display All Students
3. Search Student by Roll No
4. Update Student Marks
5. Delete Student
6. Exit
Enter your choice: 2

Roll Name Marks


------------------------------
1 Amrit 98
2 Rahul 90
3 Sneha 92
5 Rohan 88

Enter your choice: 6


Exiting program...

You might also like