Python .13 18
Python .13 18
Practical-13
Aim: Using concept of regular expressions, write a program to check the
validity of password input by users.
Code:
import re
def check_password(password):
# At least 1 letter between [a-z]
if not re.search("[a-z]", password):
return False
return True
# Example usage
password = input("Enter your password: ")
if check_password(password):
print("Valid password")
else:
print("Invalid password")
Output:
Practical-14
Aim: a. Define a class named “Institute” and its subclass “Branch”. The
Institute class has a function that
takes two values as arguments “course” and “semester” to initialize
object of both classes. Subclass
Branch has its own attributes “name” and “enrollment_no”. “Institute”
class has display() method
to print course and semester details of student. “Branch” class also has
method called display() to
print value of name and enrollment_no.
Code:
class Institute:
def __init__(self, course, semester):
self.course = course
self.semester = semester
def display(self):
print("Course:", self.course)
print("Semester:", self.semester)
class Branch(Institute):
def __init__(self, course, semester, name, enrollment_no):
super().__init__(course, semester)
self.name = name
self.enrollment_no = enrollment_no
def display(self):
super().display()
print("Name:", self.name)
print("Enrollment No:", self.enrollment_no)
# Example usage:
student = Branch("Computer Science", "3rd", "Makani Jenshi", "202203103510061")
student.display()
Output:
Code:
class Grand_father:
def __init__(self, name):
self.name = name
# def show(self):
# print("Name", self.name)
class Father(Grand_father):
def __init__(self,name,city):
super().__init__(name)
self.city =city
class Child(Father):
def __init__(self,name,city,age):
super().__init__(name,city)
self.age= age
def show(self):
#super().show()
print("Name:", self.name)
print("City:", self.city)
print("Age:", self.age)
# Example usage:
Child = Child("Jenshi", "Surat", 19)
Child.show()
Output:
Practical-15
Aim: Write a python program that
b. Reads data from text file in reverse order and write it into another file.
Code:
# Write mode ('w'): Create a new file and write to it
with open('example.txt', 'w') as file:
file.write('This is a test.\n')
# Read mode with file pointer ('r+'): Read and write to an existing file
with open('example.txt', 'r+') as file:
content = file.read()
print(content)
file.write('Writing more data.')
# Read mode with file pointer ('r+'): Read and write to an existing file at a specific position
with open('example.txt', 'r+') as file:
file.seek(0, 2) # Move the file pointer to the end of the file
file.write('\nAdding at the end.')
# Read and write mode ('w+'): Create a new file and read/write to it
with open('example2.txt', 'w+') as file:
file.write('Writing and reading.\n')
file.seek(0) # Move the file pointer to the beginning of the file
content = file.read()
print(content)
# Append and read mode ('a+'): Open an existing file for reading and writing (appending)
with open('example2.txt', 'a+') as file:
file.write('Appending and reading.\n')
file.seek(0) # Move the file pointer to the beginning of the file
content = file.read()
print(content)
Output:
b) Reads data from text file in reverse order and write it into another
file.
Code:
# Reading data from a text file in reverse order and writing it into another file
def reverse_file_content():
with open("N1.txt", "r") as file:
lines = file.readlines()
with open("reversed_N2.txt", "w") as file:
for line in reversed(lines):
file.write(line)
# Read data from text file in reverse order and write it into another file
reverse_file_content()
print("Data from 'example.txt' has been written to 'reversed_demo_file.txt' in reverse
order.")
Output:
Practical-16
Aim: a. Write a python program that reads a text file and performs the
following.
- Write first N lines of source file into another file.
- Find current position of location pointer in file
- Reset location pointer to 5th character position of file.
b. Write a python program that reads a text file and performs the
following:
- Count the number of lines
- Count number of unique words
- Count occurrence of each word
a) Write a python program that reads a text file and performs the
following.
- Write first N lines of source file into another file.
- Find current position of location pointer in file
- Reset location pointer to 5th character position of file.
Code:
def process_text_file(example, destination_file, n_lines):
# Write first N lines of example file into another file
with open(example, "r") as f_source:
lines_to_write = [next(f_source) for _ in range(n_lines)]
with open(destination_file, "w") as f_dest:
f_dest.writelines(lines_to_write)
if __name__ == "__main__":
example = "example.txt"
destination_file = "destination.txt"
n_lines = 3
current_pos, fifth_char_pos = process_text_file(example, destination_file, n_lines)
print("Current position of location pointer in file:", current_pos)
print("Reset location pointer to 5th character position of file:", fifth_char_pos)
Output:
b) Write a python program that reads a text file and performs the
following:
- Count the number of lines
- Count number of unique words
- Count occurrence of each word
Code:
def count_lines(file_path):
with open(file_path, 'r') as file:
line_count = sum(1 for _ in file)
return line_count
def count_unique_words(file_path):
unique_words = set()
with open(file_path, 'r') as file:
for line in file:
words = line.split()
unique_words.update(words)
return len(unique_words)
def count_word_occurrences(file_path):
word_occurrences = {}
with open(file_path, 'r') as file:
for line in file:
words = line.split()
for word in words:
word_occurrences[word] = word_occurrences.get(word, 0) + 1
return word_occurrences
if __name__ == "__main__":
file_path = "example.txt" # Replace with your file path
num_lines = count_lines(file_path)
print("Number of lines:", num_lines)
num_unique_words = count_unique_words(file_path)
print("Number of unique words:", num_unique_words)
word_occurrences = count_word_occurrences(file_path)
print("Word occurrences:")
for word, count in word_occurrences.items():
print(word, ":", count)
Output:
Practical-17
Aim: a. Write a python program that will call respective exception errors
in the following cases:
Code:
#Case 1
try:
numerator = 10
denominator = 0
result = numerator / denominator
except ZeroDivisionError as e:
print("Error:", e)
# Case 2
try:
with open("python2.txt", "r") as file:
content = file.read()
except FileNotFoundError as e:
print("Error:", e)
# Case 3
code = print("Hello, World"
try:
compiled_code = compile(code, "<string>", "exec")
exec(compiled_code)
except SyntaxError as e:
print("SyntaxError:", e)
Output:
b) Write a python code that will raise an exception if the user’s age is not
eligible for voting.
Code:
def check_voting_eligibility(age):
if age < 18:
raise ValueError("Sorry, you are not eligible for voting.")
if __name__ == "__main__":
try:
age = int(input("Please enter your age: "))
check_voting_eligibility(age)
print("You are eligible for voting!")
except ValueError as ve:
print(ve)
Output:
Practical-18
Code:
import sqlite3
# Create a connection to the database (or create it if it doesn't exist)
conn = sqlite3.connect('Course.db')
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
Output: