Write a program to Python program to implement various file operations.
with open('example.txt', 'r') as file:
# Get the current position of the file pointer using tell()
position = file.tell()
print("Current position of file pointer:", position)
# Read the first 10 characters of the file
data = file.read(10)
print("Data read from file:", data)
# Move the file pointer to the 20th character of the file
file.seek(20)
# Read the next 10 characters of the file from the 20th character onwards
data = file.read(10)
print("Data read from file:", data)
# Get the new position of the file pointer using tell()
position = file.tell()
print("Current position of file pointer:", position)
Write a program to Python program to demonstrate use of regular expression for
suitable application.
import re
email = input("Enter an email address: ")
# Define a regular expression pattern to validate email addresses
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
# Use the match() function to check if the email address matches the pattern
if re.match(pattern, email):
print("Valid email address")
else:
print("Invalid email address")
Write a Program to demonstrate concept of threading and multitasking in Python.
import threading
def print_cube(num):
print("\nCube:",format(num*num*num))
def print_square(num):
print("\nSquare:",format(num*num))
if __name__=="__main__":
t1=threading.Thread(target=print_square,args=(10,))
t2=threading.Thread(target=print_cube,args=(10,))
t1.start()
t2.start()
t1.join()
t2.join()
print("Done!")
#another example
import threading
import time
def task1():
for i in range(5):
print("Task 1 is running...")
time.sleep(1)
def task2():
for i in range(5):
print("Task 2 is running...")
time.sleep(1)
# Create two threads for task1 and task2
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
# Start the threads
t1.start()
t2.start()
# Wait for the threads to finish
t1.join()
t2.join()
print("All tasks are done!")
Write a Python Program to work with databases in Python to perform operations such
as
a. Connecting to database
import sqlite3
# Connect to the database
conn = sqlite3.connect('example.db')
# Create a cursor object
cursor = conn.cursor()
# Execute a query
cursor.execute("SELECT sqlite_version();")
# Fetch the result
result = cursor.fetchone()
# Print the result
print("SQLite version:", result[0])
# Close the connection
conn.close()
b. Creating and dropping tables
import sqlite3
# Connect to the database
conn = sqlite3.connect('example.db')
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
# Create a table named 'students'
cursor.execute('''CREATE TABLE students
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
# Commit the changes to the database
conn.commit()
# Drop the table named 'students'
cursor.execute('''DROP TABLE students''')
# Commit the changes to the database
conn.commit()
# Close the connection
conn.close()
c. Inserting and updating into tables
import sqlite3
# Connect to the database
conn = sqlite3.connect('example.db')
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
# Insert a new row into the 'students' table
cursor.execute('''INSERT INTO students (name, age) VALUES (?, ?)''', ('David', 23))
# Commit the changes to the database
conn.commit()
# Update the age of a student
cursor.execute('''UPDATE students SET age = ? WHERE name = ?''', (10,'David'))
# Commit the changes to the database
conn.commit()
# Select all data from the 'students' table
cursor.execute('''SELECT * FROM students''')
# Fetch all the data and print it
data = cursor.fetchall()
print(data)
# Close the connection
conn.close()
Write a Python Program to demonstrate different types of exception handing
try:
a = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# Example 2: Handling multiple exceptions
try:
a = int("hello")
except ValueError:
print("Invalid value")
except ZeroDivisionError:
print("Cannot divide by zero")
# Example 3: Handling all exceptions
try:
a = 10 / 0
except:
print("An error occurred")
# Example 4: raising an exception exceptions
x = -1
if x < 0:
raise ValueError("Value cannot be negative")
Write a GUI Program in Python to design application that demonstrates
a. Different fonts and colors
from tkinter import *
root=Tk()
root.geometry("300x150")
w=Label(root,text="frame widget demo",font=("50"))
w.pack()
frame=Frame(root)
frame.pack()
bottomframe=Frame(root)
bottomframe.pack(side=BOTTOM)
b1_button=Button(frame,text="Red",bg="Red")
b1_button.pack(side=LEFT)
b2_button=Button(frame,text='Brown',bg="Brown")
root.mainloop()
b. Different Layout Managers
from tkinter import *
top=Tk()
l1=Label(top,text="DBMS")
l1.place(x=10,y=10)
e1=Entry(top,bd=5)
e1.place(x=60,y=10)
l2=Label(top,text="CG")
l2.place(x=10,y=50)
e2=Entry(top,bd=5)
e2.place(x=60,y=50)
l3=Label(top,text="AE")
l3.place(x=10,y=150)
top.geometry()
top.mainloop()
c. Event Handling
import tkinter as tk
# Create the main window
window = tk.Tk()
window.title("Event Handling")
# Create some widgets
label = tk.Label(window, text="Click the button")
button = tk.Button(window, text="Click me!")
# Define a function to handle button clicks
def handle_click():
label.config(text="Button clicked!")
# Bind the button to the handle_click() function
button.config(command=handle_click)
# Pack the widgets into the window
label.pack()
button.pack()
# Start the event loop
window.mainloop()
7. Write Python Program to create application which uses date and time in Python
import datetime
current_time=datetime.datetime.now()
print("The attribute of now()are:")
print("Year:",end=" ")
print(current_time.year)
print("Month:",end=" ")
print(current_time.month)
print("Hour:",end=" ")
print(current_time.hour)
#Combine date and time
from datetime import *
d=date(2022,1,1)
t=time(10,30)
dt=datetime.combine(d,t)
print(dt)
#time object using time() function
from datetime import datetime
time=datetime.now().time()
print("Current Time=",time)
8. Write a Python program to create server-client and exchange basic information
import socket
import sys
import threading
sckt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('103.241.135.138', 9999)
sckt.connect(server_address)
def client_send():
while True:
message = raw_input("Text:")
sckt.send(message)
def client_recv():
while True:
reply = sckt.recv(1024)
print("Received", repr(reply))
thread_send = []
thread_recv = []
num_threads = 10
for loop_1 in range(num_threads):
thread_send.append(threading.Thread(target=client_send))
thread_send[-1].start()
for loop_2 in range(num_threads):
thread_recv.append(threading.Thread(target=client_recv))
thread_recv[-1].start()
Write a program to Python program to implement concepts of OOP such as
a. Types of Methods
class Rectangle:
shape = "rectangle" # Class variable
def __init__(self, width, height):
self.width = width # Instance variable
self.height = height # Instance variable
def area(self):
return self.width * self.height # Instance method
@classmethod
def change_shape(cls, new_shape):
cls.shape = new_shape # Class method to change class variable
@staticmethod
def is_square(width, height):
return width == height # Static method to check if dimensions make a square
# Create an instance of Rectangle with width 5 and height 10
rect = Rectangle(5, 10)
# Call instance method area() on the instance
print("Area of rectangle:", rect.area())
# Call class method change_shape() to change class variable shape
Rectangle.change_shape("square")
# Print the new value of class variable shape after changing it
print("Shape of rectangle:", rect.shape)
# Call static method is_square() to check if dimensions make a square
print("Is this a square?", Rectangle.is_square(5, 10))
b. Inheritance
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
pass # Define this method in subclass
class Dog(Animal):
def __init__(self, name):
super().__init__(name, species="dog")
def make_sound(self):
return "Woof!"
class Cat(Animal):
def __init__(self, name):
super().__init__(name, species="cat")
def make_sound(self):
return "Meow!"
# Create instances of Dog and Cat
dog = Dog("Fido")
cat = Cat("Whiskers")
# Call instance methods
print(dog.name, dog.species, dog.make_sound())
print(cat.name, cat.species, cat.make_sound())
c. Polymorphism
class Shape:
def area(self):
pass # Define this method in subclass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
def get_area(shape):
return shape.area()
# Create instances of Rectangle and Triangle
rect = Rectangle(5, 10)
tri = Triangle(5, 10)
# Call the get_area function with different shapes
print("Area of rectangle:", get_area(rect))
print("Area of triangle:", get_area(tri))
Write a program to Python program to implement concepts of OOP such as
a. Abstract methods and classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
# Create instances of Rectangle and Circle
rect = Rectangle(5, 10)
circ = Circle(3)
# Call the area method on the shapes
print("Area of rectangle:", rect.area())
print("Area of circle:", circ.area())
b. Interfaces
from abc import ABC, abstractmethod
# Define an abstract Printable class with a print method
class Printable(ABC):
@abstractmethod
def print(self):
pass
# Define a Document class that implements Printable
class Document(Printable):
def __init__(self, title, content):
self.title = title
self.content = content
def print(self):
print("Title:", self.title)
print("Content:", self.content)
# Define an Image class that implements Printable
class Image(Printable):
def __init__(self, name):
self.name = name
def print(self):
print("Image:", self.name)
# Create instances of Document and Image
doc = Document("My Document", "Lorem ipsum dolor sit amet.")
img = Image("my_image.jpg")
# Call the print method on the printables
doc.print()
img.print()