Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Python_Practicals

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

Python_Practicals

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

1. Read a text file line by line and display each word separated by #.

------------------------------------------------------------------
def task1(filename):
with open(filename, 'r') as file:
for line in file:
words = line.strip().split()
print('#'.join(words))

# Example:
task1('example.txt')

Output:
Hello#world
Python#programming#is#fun

2. Count vowels, consonants, uppercase, and lowercase characters.


------------------------------------------------------------------
def task2(filename):
vowels = "aeiouAEIOU"
with open(filename, 'r') as file:
data = file.read()
vowel_count = sum(1 for char in data if char in vowels)
consonant_count = sum(1 for char in data if char.isalpha() and char not in
vowels)
uppercase_count = sum(1 for char in data if char.isupper())
lowercase_count = sum(1 for char in data if char.islower())
print(f"Vowels: {vowel_count}, Consonants: {consonant_count}, Uppercase:
{uppercase_count}, Lowercase: {lowercase_count})

# Example:
task2('example.txt')

Output:
Vowels: 7, Consonants: 15, Uppercase: 4, Lowercase: 18

3. Remove all lines containing the character 'a' and write them to another file.
------------------------------------------------------------------
def task3(input_file, output_file):
with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
for line in infile:
if 'a' not in line:
outfile.write(line)

# Example:
task3('example.txt', 'output.txt')

Output (output.txt):
Python is fun
Life is great

4. Create a binary file with name and roll number. Search for a roll number.
------------------------------------------------------------------
import pickle

def task4_create(file_name, data):


with open(file_name, 'wb') as file:
pickle.dump(data, file)

def task4_search(file_name, roll_number):


with open(file_name, 'rb') as file:
data = pickle.load(file)
result = next((item['name'] for item in data if item['roll'] ==
roll_number), None)
print(f"Name: {result}" if result else "Roll number not found")

# Example:
data = [{'roll': 1, 'name': 'John'}, {'roll': 2, 'name': 'Jane'}]
task4_create('students.dat', data)
task4_search('students.dat', 1)

Output:
Name: John

5. Update marks for a roll number in a binary file.


------------------------------------------------------------------
def task5_update(file_name, roll_number, new_marks):
with open(file_name, 'rb') as file:
data = pickle.load(file)
for item in data:
if item['roll'] == roll_number:
item['marks'] = new_marks
with open(file_name, 'wb') as file:
pickle.dump(data, file)
print("Marks updated")

# Example:
task5_update('students.dat', 1, 95)

Output:
Marks updated

6. Simulate a dice (random number generator 1 to 6).


------------------------------------------------------------------
import random

def task6():
print(random.randint(1, 6))

# Example:
task6()

Output:
4

7. Implement a stack using a list.


------------------------------------------------------------------
def task7():
stack = []

def push(item):
stack.append(item)
def pop():
if stack:
return stack.pop()
else:
print("Stack is empty")

def display():
print(stack)

# Example operations
push(10)
push(20)
display()
pop()
display()

task7()

Output:
[10, 20]
[10]

8. Create a CSV file and search for a password by user ID.


------------------------------------------------------------------
import csv

def task8():
# Create CSV file
with open('users.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['user_id', 'password'])
writer.writerow(['user1', 'pass123'])
writer.writerow(['user2', 'pass456'])

# Search password
user_id_to_search = 'user1'
with open('users.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
if row['user_id'] == user_id_to_search:
print(f"Password for {user_id_to_search}: {row['password']}")

# Example:
task8()

Output:
Password for user1: pass123

9. Database management: Create a table, insert data, and perform SQL operations.
------------------------------------------------------------------
import sqlite3

def database_management():
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
# Create table
cursor.execute('''CREATE TABLE IF NOT EXISTS student (
roll INTEGER PRIMARY KEY,
name TEXT,
marks REAL)''')

# Insert data
cursor.execute("INSERT INTO student (roll, name, marks) VALUES (1, 'John',
85.5)")
cursor.execute("INSERT INTO student (roll, name, marks) VALUES (2, 'Jane',
90.0)")
conn.commit()

# Update marks
cursor.execute("UPDATE student SET marks = 95.0 WHERE roll = 1")

# Order by marks
cursor.execute("SELECT * FROM student ORDER BY marks DESC")
print(cursor.fetchall())

# Group by and aggregate functions


cursor.execute("SELECT AVG(marks) FROM student")
print(f"Average marks: {cursor.fetchone()[0]}")

conn.close()

# Example:
database_management()

Output:
[(1, 'John', 95.0), (2, 'Jane', 90.0)]
Average marks: 92.5

You might also like