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

Computer Practical Programs

Uploaded by

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

Computer Practical Programs

Uploaded by

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

Computer Practical Programs

1. Read Text from a file


with open('file.txt', 'r') as file:
for line in file:
words = line.split()
for word in words:
print(word, end=" ")

2. Read a text file and display the number of vowels/consonants/uppercase/lowercase letters:

vowels = "aeiouAEIOU"
with open("file.txt", "r") as file:
text = file.read()

vowel_count = consonant_count = upper_count = lower_count = 0


for char in text:
if char.isalpha():
if char in vowels:
vowel_count += 1
else:
consonant_count += 1
if char.isupper():
upper_count += 1
else:
lower_count += 1
print(
f"Vowels: {vowel_count}, Consonants: {consonant_count}, Uppercase: {upper_count}, Lowercase:
{lower_count}"
)

Output:

Vowels: 65, Consonants: 119, Uppercase: 16, Lowercase: 168

3. Create a binary file with name and roll no. Search for a roll no and display the name:

import pickle

def write_binary_file():
students = {101: 'Alice', 102: 'Bob', 103: 'Charlie'}
with open('students.dat', 'wb') as file:
pickle.dump(students, file)

def search_roll_no(roll_no):
with open('students.dat', 'rb') as file:
students = pickle.load(file)
name = students.get(roll_no, "Not Found")
print(f"Roll No: {roll_no}, Name: {name}")

write_binary_file()
search_roll_no(102)

4. Implement a stack using a list:

stack = []

def push(item)
stack.append(item)
print(f"Pushed {item} onto the stack.")

def pop():
if is_empty():
return "Stack is empty, cannot pop."
return stack.pop()

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

def peek():
if is_empty():
return "Stack is empty."
return stack[-1]

def display_stack():
print("Stack:", stack)

display_stack()
push(10)
push(20)
push(30)
display_stack()

print(f"Popped element: {pop()}")


display_stack()

print(f"Top element: {peek()}")


display_stack()
Output:
Stack: []

Pushed 10 onto the stack.


Pushed 20 onto the stack.

Pushed 30 onto the stack.


Stack: [10, 20, 30]

Popped element: 30
Stack: [10, 20]

Top element: 20
Stack: [10, 20]

5. Function to sum all integers from list L ending with digit 3:

def SUM3(L):
total = 0
for num in L:
if str(num).endswith("3"):
total += num
print(total)

L = [123, 12, 34, 53, 23, 10]


SUM3(L)

6. Sort a list using bubble sort and display in ascending and descending order:
def bubble_sort(arr, reverse=False):
n = len(arr)
for i in range(n-1):
for j in range(n-i-1):
if (arr[j] > arr[j+1] and not reverse) or (arr[j] < arr[j+1] and reverse):
arr[j], arr[j+1] = arr[j+1], arr[j]

def display_sorted_list():
L = [64, 25, 12, 22, 11]
bubble_sort(L)
print("Ascending:", L)
bubble_sort(L, reverse=True)
print("Descending:", L)

display_sorted_list()

7. Find the word with the maximum length in a line of text:

def find_max_length_word(text):
words = text.split()
max_word = ""
for word in words:
if len(word) > len(max_word):
max_word = word
print(f"Word with max length: {max_word}")

text = input("Enter a line of text: ")


find_max_length_word(text)

8. Check if a string is a palindrome:


def is_palindrome(text):
text = text.lower()
return text == text[::-1]

text = input("Enter a string: ")


if is_palindrome(text):
print(f"{text} is a palindrome")
else:
print(f"{text} is not a palindrome")

def is_palindrome(text):
text = text.lower()
return text == text[::-1]

text = input("Enter a string: ")


if is_palindrome(text):
print(f"{text} is a palindrome")
else:
print(f"{text} is not a palindrome")

9. Input data in CSV and display it:

import csv

def write_csv():
with open('stu.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Roll', 'Name', 'Stream', 'Marks'])
writer.writerow([1, 'Alice', 'CS', 90])
writer.writerow([2, 'Bob', 'Math', 85])
def read_csv():
with open('stu.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)

write_csv()
read_csv()

10. Store names and phone numbers in a dictionary and search for a name:

def phone_directory():
directory = {}
for _ in range(int(input("Enter number of entries: "))):
name = input("Enter name: ")
phone = input("Enter phone number: ")
directory[name] = phone

search_name = input("Enter name to search: ")


print(f"Phone number: {directory.get(search_name, 'Not found')}")

phone_directory()

SQL Questions
1. Employee and Department Queries:
/* a.> */ SELECT deptid, MAX(salary), MIN(salary) FROM Employee GROUP BY deptid;
/* b.> */ SELECT name FROM Employee WHERE name LIKE 'a%';
/* c.> */ SELECT Employee.name, Department.deptname FROM Employee JOIN Department ON Employee.deptid =
Department.deptid;
/* d.> */ SELECT name, empid FROM Employee ORDER BY dob;
/* e.> */ UPDATE Employee SET salary = 95000 WHERE name = 'Ramesh';

2. Student Queries:

/* a.> */ SELECT * FROM student ORDER BY average DESC;


/* b.> */ SELECT name FROM student WHERE stipend IS NOT NULL;
/* c.> */ SELECT name FROM student WHERE name LIKE 'A%';
/* d.> */ UPDATE student SET stipend = 1555 WHERE name = 'Anup';
/* e.> */ SELECT division, COUNT(*) FROM student GROUP BY division;

Python-MySQL Connectivity
# A.
import mysql.connector

conn = mysql.connector.connect(host='localhost', user='root', password='password', database='school')


cursor = conn.cursor()

cursor.execute('''
CREATE TABLE student (
name VARCHAR(255),
class INT,
roll INT PRIMARY KEY,
stipend DECIMAL(10, 2)
)
''')

conn.commit()
cursor.close()
conn.close()

# B.
conn = mysql.connector.connect(host='localhost', user='root', password='password', database='school')
cursor = conn.cursor()

cursor.execute("SELECT * FROM student")


for row in cursor.fetchall():
print(row)

cursor.close()
conn.close()

# C.
conn = mysql.connector.connect(host='localhost', user='root', password='password', database='school')
cursor = conn.cursor()

cursor.execute("INSERT INTO student (name, class, roll, stipend) VALUES ('Alice', 12, 101, 8000)")
cursor.execute("INSERT INTO student (name, class, roll, stipend) VALUES ('Bob', 10, 102, 9000)")

conn.commit()
cursor.close()
conn.close()

# D.
conn = mysql.connector.connect(host='localhost', user='root', password='password', database='school')
cursor = conn.cursor()

cursor.execute("UPDATE student SET stipend = 9500 WHERE roll = 101")

conn.commit()
cursor.close()
conn.close()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy