0% found this document useful (0 votes)
3 views51 pages

CBSE Class12 CS Project

The document contains various Python code snippets demonstrating fundamental programming concepts such as checking if a number is even or odd, calculating the sum of natural numbers, finding the largest of three numbers, and checking for prime numbers. It also includes operations on lists, tuples, dictionaries, file handling, and MySQL database interactions, as well as implementing a stack with push, pop, and display functionalities. Each section provides a practical example of how to implement these concepts in Python.
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)
3 views51 pages

CBSE Class12 CS Project

The document contains various Python code snippets demonstrating fundamental programming concepts such as checking if a number is even or odd, calculating the sum of natural numbers, finding the largest of three numbers, and checking for prime numbers. It also includes operations on lists, tuples, dictionaries, file handling, and MySQL database interactions, as well as implementing a stack with push, pop, and display functionalities. Each section provides a practical example of how to implement these concepts in Python.
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/ 51

Check whether a number is even or odd

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


if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
Sum of first n natural numbers using while
loop

n = int(input("Enter n: "))
i=1
s=0
while i <= n:
s += i
i += 1
print("Sum of first", n, "natural
numbers is:", s)
Find the largest of three numbers (nested
if)

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


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b:
if a >= c:
largest = a
else:
largest = c
else:
if b >= c:
largest = b
else:
largest = c

print("The largest number is:", largest)


Check if a number is prime
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
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")
Sum and average of list elements
nums = [12, 45, 67, 23, 90]
total = sum(nums)
avg = total / len(nums)
print("List:", nums)
print("Sum:", total)
print("Average:", avg)
Count frequency of elements in a list
lst = [1, 2, 2, 3, 3, 3, 4]
freq = {}
for item in lst:
freq[item] = [Link](item, 0) + 1
print("Frequency of elements:", freq)
Tuple operations
tup = (10, 20, 30, 40, 50)
print("Tuple:", tup)
print("Length:", len(tup))
print("Max:", max(tup))
print("Min:", min(tup))
Dictionary – add, update, delete
student = {"name": "Sam", "age": 17,
"grade": "A"}
print("Original dictionary:", student)
student["school"] = "CBSE"
student["grade"] = "A+"
del student["age"]
print("Updated dictionary:", student)
Function to find factorial
def factorial(n):
fact = 1
for i in range(1, n + 1):
fact *= i
return fact

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


print("Factorial of", num, "is",
factorial(num))
Function to check palindrome

def is_palindrome(s):
return s == s[::-1]

text = input("Enter string: ")


if is_palindrome(text):
print("Palindrome")
else:
print("Not Palindrome")
Function to calculate simple interest

def simple_interest(p, r, t):


return (p * r * t) / 100

p = float(input("Enter principal: "))


r = float(input("Enter rate: "))
t = float(input("Enter time: "))
print("Simple Interest:",
simple_interest(p, r, t))
Function to find max of list
def max_in_list(lst):
return max(lst)

lst = [12, 56, 23, 78, 45]


print("Maximum number:",
max_in_list(lst))
Write and read from a text file
f = open("[Link]", "w")
[Link]("Hello CBSE
Students!\nWelcome to Python file
handling.")
[Link]()

f = open("[Link]", "r")
print([Link]())
[Link]()
Count words in a text file
f = open("[Link]", "r")
data = [Link]()
words = [Link]()
print("Number of words:",
len(words))
[Link]()
Binary file write and read
import pickle
data = {"name": "Samarth", "marks":
90}
with open("[Link]", "wb") as f:
[Link](data, f)

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


obj = [Link](f)
print("Data from binary file:", obj)
Write and read CSV file
import csv
with open("[Link]", "w",
newline="") as f:
writer = [Link](f)
[Link](["Name", "Age",
"Marks"])
[Link](["Samarth", 17,
90])
[Link](["Aman", 18, 85])

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


reader = [Link](f)
for row in reader:
print(row)
Connect to MySQL

import [Link]

con = [Link](host="localhost",
user="root", password="yourpassword")
if con.is_connected():
print("Connection successful!")
[Link]()
Create database and table
import [Link]

con = [Link](host="localhost",
user="root", password="yourpassword")
cur = [Link]()
[Link]("CREATE DATABASE IF NOT EXISTS
school")
[Link]("USE school")
[Link]("CREATE TABLE IF NOT EXISTS
student (roll INT PRIMARY KEY, name
VARCHAR(30), marks INT)")
print("Database and table created successfully!")
[Link]()
Insert and display records
import [Link]

con = [Link](host="localhost",
user="root", password="yourpassword",
database="school")
cur = [Link]()

[Link]("INSERT INTO student VALUES (1,


'Samarth', 90)")
[Link]("INSERT INTO student VALUES (2,
'Aman', 85)")
[Link]()

[Link]("SELECT * FROM student")


data = [Link]()
for row in data:
print(row)

[Link]()
Update and delete record
import [Link]

con = [Link](host="localhost",
user="root", password="yourpassword",
database="school")
cur = [Link]()

[Link]("UPDATE student SET marks = 95


WHERE roll = 1")
[Link]()

[Link]("DELETE FROM student WHERE roll =


2")
[Link]()

print("Records updated and deleted


successfully!")
[Link]()
Stacks full program with Push, Pop, Peek,
Display, and is menu-driven

stack = []

def push():
element = input("Enter element to push: ")
[Link](element)
print(element, "pushed to stack.")

def pop():
if not stack:
print("Stack Underflow! (No elements to pop)")
else:
element = [Link]()
print("Popped element:", element)

def peek():
if not stack:
print("Stack is empty!")
else:
print("Top element is:", stack[-1])

def display():
if not stack:
print("Stack is empty!")
else:
print("Stack elements are:")
for i in range(len(stack)-1, -1, -1):
print(stack[i])

while True:
print("\n*** STACK OPERATIONS MENU ***")
print("1. PUSH")
print("2. POP")
print("3. PEEK (Top element)")
print("4. DISPLAY STACK")
print("5. EXIT")
choice = input("Enter your choice (1-5): ")

if choice == '1':
push()
elif choice == '2':
pop()
elif choice == '3':
peek()
elif choice == '4':
display()
elif choice == '5':
print("Exiting program...")
break
else:
print("Invalid choice! Please enter between 1 to 5.")

You might also like