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

Arnam Program File

Uploaded by

Naruto Uzumaki
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Arnam Program File

Uploaded by

Naruto Uzumaki
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

LUCKNOW PUBLIC SCHOOL

PROGRAM FILE

COMPUTER SCIENCE (083)

AISSCE PRACTICAL EXAMINATION


2024-25

SUBMITTED BY: Arnam Singh Chauhan

ROLL NO: ________________

1
TABLE OF CONTENT

S.No. TOPIC
1 XI- Review & Working
with Functions
2 Data File Handling
3 Stack
4 Database Connectivity
5 SQL Queries

2
Working with Functions
1. Fibonacci Sequence
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fibonacci(12))

2. Prime Number Check


def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i=5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True
print(is_prime(51))

3. Factorial
def factorial(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
print(factorial(7))

4. Palindrome Check
def is_palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:

3
return False
return is_palindrome(s[1:-1])
print(is_palindrome('Madam'))

5. Armstrong Number Check (Loop with String Manipulation)


def is_armstrong(num):
s = str(num)
power = len(s)
return sum(int(d) ** power for d in s) == num
print(is_armstrong(153))

6. Permutations of a String
def string_permutations(s):
if len(s) == 1:
return [s]
perm_list = []
for i in range(len(s)):
for perm in string_permutations(s[:i] + s[i+1:]):
perm_list.append(s[i] + perm)
return perm_list
print(string_permutations('abc'))

7. GCD
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd(144,225))

8. Decimal to Binary Conversion (Bitwise Operations)


def decimal_to_binary(n):
binary = ""
while n > 0:
binary = str(n % 2) + binary
n //= 2
return binary if binary else "0"
print(decimal_to_binary(5.134))

4
9. 11. List Reversal (Using List)
def reverse_list(lst):
reversed_lst = []
for item in lst[::-1]:
reversed_lst.append(item)
return reversed_lst
print(reverse_list([1,2,3,4,5]))

10. Hangman Game


import random

def hangman(word_list):
word = random.choice(word_list).upper()
guessed_letters = []
tries = 6
display = ['_' for _ in word]

print("Let's play Hangman!")


print("Word to guess:", ' '.join(display))

while tries > 0 and '_' in display:


guess = input("Guess a letter: ").upper()

if len(guess) != 1 or not guess.isalpha():


print("Please enter a single valid letter.")
continue

if guess in guessed_letters:
print("You've already guessed that letter.")
continue

guessed_letters.append(guess)

if guess in word:
print(f"Good job! {guess} is in the word.")
for i, letter in enumerate(word):
if letter == guess:
display[i] = guess
else:
tries -= 1

5
print(f"Wrong guess. {tries} tries left.")

print(' '.join(display))

if '_' not in display:


print(f"Congratulations! You guessed the word: {word}")
else:
print(f"Game over! The word was: {word}")

# Example usage
word_list = ['python', 'hangman', 'challenge', 'developer']
hangman(word_list)

6
Data File Handling
11. Count Vowels and Consonants in the file

def count_vowels_consonants(filename):
vowels = "AEIOUaeiou"
v_count = c_count = 0

with open(filename, 'r') as file:


for line in file:
for char in line:
if char.isalpha():
if char in vowels:
v_count += 1
else:
c_count += 1

print(f"Vowels: {v_count}, Consonants: {c_count}")

count_vowels_consonants('sample.txt')

12. Old and Replace Words in a Text File

def find_and_replace(filename, old_word, new_word):


with open(filename, 'r') as file:
data = file.read()

data = data.replace(old_word, new_word)

with open(filename, 'w') as file:


file.write(data)

print(f"Replaced '{old_word}' with '{new_word}' successfully.")

find_and_replace('sample.txt', 'Python', 'Java')

13. Read and Display CSV File Content

7
import csv

def display_csv(filename):
with open(filename, newline='') as file:
reader = csv.reader(file)
for row in reader:
print(row)

display_csv('data.csv')

14. Write Student Data to CSV File

import csv

def write_student_data(filename, student_data):


with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Class', 'Marks'])
writer.writerows(student_data)

data = [
['Alok', '12A', 85],
['Riya', '12B', 90],
['Karan', '12C', 78]
]

write_student_data('students.csv', data)

15. Store and Retrieve Dictionary in a Binary File

import pickle

8
def write_binary(filename, data):
with open(filename, 'wb') as file:
pickle.dump(data, file)
print("Data written to binary file.")

def read_binary(filename):
with open(filename, 'rb') as file:
data = pickle.load(file)
print("Data retrieved:", data)

student_data = {'Alok': 85, 'Riya': 90, 'Karan': 78}

write_binary('students.dat', student_data)
read_binary('students.dat')

9
Stack Implementation
stack = []

# Push an element onto the stack


def push(element):
stack.append(element)
print(f"Pushed: {element}")

# Pop an element from the stack


def pop():
if not is_empty():
element = stack.pop()
print(f"Popped: {element}")
return element
else:
print("Stack Underflow - No elements to pop.")

# Peek at the top element of the stack


def peek():
if not is_empty():
print(f"Top Element: {stack[-1]}")
return stack[-1]
else:
print("Stack is empty.")

# Check if the stack is empty


def is_empty():
return len(stack) == 0

# Display the stack


def display():
if not is_empty():
print("Stack:", stack)
else:
print("Stack is empty.")

# Reverse the stack


def reverse():
global stack
stack = stack[::-1]
print("Stack reversed:", stack)

# Driver Code

10
if __name__ == "__main__":
push(10)
push(20)
push(30)
display()
peek()
pop()
display()
reverse()
display()

11
Database Connectivity
Connect to MySQL and Create Database

import mysql.connector

try:
conn = mysql.connector.connect(host="localhost", user="root", password="lps123")
cursor = conn.cursor()

cursor.execute("CREATE DATABASE example_db")


print("Database 'example_db' created successfully.")

except mysql.connector.Error as e:
print(f"Error: {e}")

finally:
if cursor:
cursor.close()
if conn:
conn.close()

Create Table and Insert Data


import mysql.connector

try:
conn = mysql.connector.connect(
host="localhost",
user="root",
password="lps123",
database="example_db"
)
cursor = conn.cursor()

# Creating the table


cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT

12
)
""")

# Inserting data
cursor.execute("INSERT INTO students (name, age) VALUES ('Alice', 22), ('Bob', 25)")
conn.commit()
print("Data inserted into 'students' table.")

# Fetching data
cursor.execute("SELECT * FROM students")
for row in cursor.fetchall():
print(row)

except mysql.connector.Error as e:
print(f"Error: {e}")

finally:
if cursor:
cursor.close()
if conn:
conn.close()

Update and Delete Records


import mysql.connector

try:
conn = mysql.connector.connect(
host="localhost",
user="root",
password="lps123",
database="example_db"
)
cursor = conn.cursor()

# Updating data
cursor.execute("UPDATE students SET age = 23 WHERE name = 'Alice'")

13
conn.commit()
print("Updated Alice's age to 23.")

# Deleting data
cursor.execute("DELETE FROM students WHERE name = 'Bob'")
conn.commit()
print("Deleted record of Bob.")

# Fetching remaining data


cursor.execute("SELECT * FROM students")
for row in cursor.fetchall():
print(row)

except mysql.connector.Error as e:
print(f"Error: {e}")

finally:
if cursor:
cursor.close()
if conn:
conn.close()

14
SQL Queries
-- 1. Select all records from a table
SELECT * FROM employees;

-- 2. Select specific columns


SELECT first_name, last_name FROM employees;

-- 3. Count the number of records


SELECT COUNT(*) FROM employees;

-- 4. Filter records with a WHERE clause


SELECT * FROM employees WHERE department = 'Sales';

-- 5. Order records by a column


SELECT * FROM employees ORDER BY hire_date DESC;

-- 6. Insert a new record


INSERT INTO employees (first_name, last_name, department, hire_date)
VALUES ('John', 'Doe', 'IT', '2023-01-15');

-- 7. Update existing records


UPDATE employees SET department = 'Marketing' WHERE employee_id = 10;

-- 8. Delete records
DELETE FROM employees WHERE employee_id = 15;

-- 9. Join two tables


SELECT employees.first_name, employees.last_name, departments.department_name
FROM employees
JOIN departments ON employees.department_id = departments.department_id;

-- 10. Group and aggregate data


SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;

15

You might also like