Python Programming and SQL Code - Part 1
1. Count number of alphabets, digits, alphanumeric characters from the text file story.txt:
def count_characters(file_name):
with open(file_name, 'r') as file:
content = file.read()
alphabets = sum(c.isalpha() for c in content)
digits = sum(c.isdigit() for c in content)
alphanumeric = sum(c.isalnum() for c in content)
return alphabets, digits, alphanumeric
alphabets, digits, alphanumeric = count_characters('story.txt')
print(f"Alphabets: {alphabets}, Digits: {digits}, Alphanumeric: {alphanumeric}")
2. Count words from the text file poem.txt:
def count_words(file_name):
with open(file_name, 'r') as file:
content = file.read()
words = content.split()
return len(words)
word_count = count_words('poem.txt')
print(f"Word count: {word_count}")
3. Add even and odd elements of list separately and print the sum:
def sum_even_odd(lst):
even_sum = sum(x for x in lst if x % 2 == 0)
odd_sum = sum(x for x in lst if x % 2 != 0)
return even_sum, odd_sum
even_sum, odd_sum = sum_even_odd([1, 2, 3, 4, 5, 6])
print(f"Sum of even elements: {even_sum}, Sum of odd elements: {odd_sum}")
4. Take input of name, age, salary, and designation and add it to a binary file record.dat. Fetch all records with age
greater than 35:
import pickle
def add_record(file_name, name, age, salary, designation):
with open(file_name, 'ab') as file:
pickle.dump({'name': name, 'age': age, 'salary': salary, 'designation': designation}, file)
def fetch_records(file_name):
records = []
with open(file_name, 'rb') as file:
try:
while True:
record = pickle.load(file)
if record['age'] > 35:
records.append(record)
except EOFError:
pass
return records
# Example usage
add_record('record.dat', 'John Doe', 36, 50000, 'Manager')
records = fetch_records('record.dat')
print(records)