Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Experiment 1
- import os
- file = open('demo.txt','w')
- file.write("Hello World!")
- file.close()
- file = open('demo.txt','r')
- print(file.read())
- file.close()
- with open('demo.txt','a') as file:
- file.write("\nHave a good day")
- with open('demo.txt','r') as file:
- print(file.read())
- with open('demo.txt','r') as file:
- file.seek(6)
- print(file.tell())
- content = file.read()
- print(content)
- print(file.tell())
- import os
- file = open('demo.bin','wb')
- file.write(b"Hello World!")
- file.close()
- file = open('demo.bin','rb')
- print(file.read())
- file.close()
- with open('demo.bin','ab') as file:
- file.write(b"\nHave a good day")
- with open('demo.bin','rb') as file:
- print(file.read())
- with open('demo.bin','rb') as file:
- file.seek(6)
- print(file.tell())
- content = file.read()
- print(content)
- print(file.tell())
- import zipfile
- with zipfile.ZipFile("zipped_files.zip",'w') as zipf:
- zipf.write("demo.txt")
- zipf.write("demo.bin")
- print("Files Zipped Successfully")
- with zipfile.ZipFile("zipped_files.zip",'r') as zipf:
- zipf.extractall("unzipped_files")
- print("Files Unzipped Successfully")
- if os.path.exists('demo.txt'):
- os.remove('demo.txt')
- print("File Deleted")
- else:
- print("File doesn't exist")
- if os.path.exists('demo.bin'):
- os.remove('demo.bin')
- print("File Deleted")
- else:
- print("File doesn't exist")
- import os
- with open('std_records.txt','w') as file:
- file.write('Student Name,Roll Number,Student Marks\n')
- file.write('John,1001,98\n')
- file.write('Ben,1002,84\n')
- file.write('Tom,1003,91\n')
- file.write('Adam,1004,76\n')
- file.write('Tim,1005,89')
- print("Records Inserted Successfully")
- # In[31]:
- if os.path.exists('std_records.txt'):
- with open('std_records.txt','r') as file:
- print(file.read())
- else:
- print("Student Records Doesnt Exist")
- # In[32]:
- if os.path.exists('std_records.txt'):
- roll_number = input("Enter Student Roll Number:")
- with open('std_records.txt', 'r') as file:
- header = file.readline()
- found = False
- for line in file:
- if roll_number in line:
- print(f"Record Found:\n{header}{line.strip()}")
- found = True
- break
- if not found:
- print("Record not found.")
- else:
- print("Student Records Doesnt Exist")
- # In[33]:
- with open('C:\\Users\\Student\\Pictures\\sampleimg.jpg','rb') as img:
- imagedata = img.read()
- # In[34]:
- from PIL import Image
- import matplotlib.pyplot as plt
- with open('output_image.jpg','wb') as img:
- image = img.write(imagedata)
- image = Image.open('output_image.jpg')
- plt.imshow(image)
- plt.axis("off")
- plt.show()
- # In[35]:
- import zipfile
- with zipfile.ZipFile("student_zipped.zip",'w') as zipf:
- zipf.write('std_records.txt')
- zipf.write('student_details.bin')
- print("Files Zipped Successfully")
- # In[36]:
- with zipfile.ZipFile("student_zipped.zip",'r') as zipf:
- zipf.extractall("Student Details")
- print("Files Unzipped Successfully")
- #Experiment 2
- with open('maildata.txt','r') as file:
- data = file.read()
- email_pattern = r'[a-zA-Z0-9.!$%-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,}'
- emails = re.findall(email_pattern, data)
- for email in emails:
- print(email)
- with open('phdata.txt','r') as file:
- data = file.read()
- pattern = r'\+?\(?(\d{1,3})?\)?[\s\-]?\(?(\d{3})\)?[\s\-]?(\d{3})[\s\-]?(\d{4})'
- phnos = re.findall(pattern,data)
- print(phnos)
- for num in phnos:
- print(''.join(num))
- import re
- file_path = "demodata.txt"
- with open(file_path, 'r') as file:
- content = file.read()
- hashtags = re.findall(r"#\w+", content)
- print("Extracted Hashtags:", hashtags)
- #Experiment 3
- with open('demo1.html','r') as file:
- data = file.read()
- title_pattern = r'<title>(.*)?</title>'
- titles = re.findall(title_pattern,data,re.IGNORECASE)
- print(f'Title: {titles}')
- head_pattern = r'<h[1-6]>(.*)?</h[1-6]>'
- heads = re.findall(head_pattern,data,re.IGNORECASE)
- print(f'Heading: {heads}')
- p_pattern = r'<p>(.*)?</p>'
- ps = re.findall(p_pattern,data,re.IGNORECASE)
- print(f'Paras: {ps}')
- link_pattern = r'<a\s+href=["\'](.*)?["\']>'
- links = re.findall(link_pattern,data,re.IGNORECASE)
- print(f'Links: {links}')
- #Experiment 4
- import threading as t
- def square(num):
- print(f"Square of {num} is {num**2}")
- def cube(num):
- print(f"Cube of {num} is {num**3}")
- number = int(input("Enter a number to find square and cube:"))
- thread1 = t.Thread(target=square,args=(number,))
- thread2 = t.Thread(target=cube,args=(number,))
- thread1.start()
- thread2.start()
- thread1.join()
- thread2.join()
- print("Both threads have executed successfully")
- import threading as t
- import time
- def print_numbers():
- for i in range(1,6):
- print(f"Number: {i}")
- time.sleep(1)
- def print_alphabets():
- for char in 'ABCDE':
- print(f"Alphabet: {char}")
- time.sleep(1)
- thread1 = t.Thread(target=print_numbers)
- thread2 = t.Thread(target=print_alphabets)
- thread1.start()
- thread2.start()
- thread1.join()
- thread2.join()
- print("Both threads have executed successfully")
- #Experiment 5
- from datetime import datetime
- import time
- def show_current_time():
- now = datetime.now()
- print("Current Date and Time:",now.strftime("%Y-%m-%d %H:%M:%S"))
- def set_alarm(hour,minute):
- print(f"Alarm set for {hour}:{minute}. Waiting to ring...")
- while True:
- now = datetime.now()
- if now.hour == hour and now.minute == minute:
- print("It is time to wake up!!")
- print("📢📢📢📢📢📢📢📢📢")
- break
- time.sleep(10)
- def calc_date_diff(date1,date2):
- d1 = datetime.strptime(date1,"%Y-%m-%d")
- d2 = datetime.strptime(date2,"%Y-%m-%d")
- diff = abs((d2-d1).days)
- print(f"The difference between {date1} and {date2} is {diff} days.")
- print("Date and Time Application")
- while True:
- print("1. Show Current Date & Time")
- print("2. Set an Alarm")
- print("3. Calculate Date Difference")
- print("4. Exit")
- choice = input("Enter your choice:")
- if (choice=='1'):
- show_current_time()
- elif (choice=='2'):
- hour = int(input("Enter hour (24-hour format):"))
- minute = int(input("Enter minute:"))
- set_alarm(hour,minute)
- elif (choice=='3'):
- date1 = input("Enter 1st date (YYYY-MM-DD):")
- date2 = input("Enter 2nd date (YYYY-MM-DD):")
- calc_date_diff(date1,date2)
- elif (choice=='4'):
- print("Exiting")
- break
- else:
- print("Invalid choice. Please try again.")
- from datetime import datetime, timedelta
- def pass_date(year, month, date, hour, minute, second, msecond):
- return datetime(year, month, date, hour, minute, second, msecond)
- year, month, date, hour, minute, second, msecond = map(int, input("Enter your date object in the format 'year month date hour minute second msecond':").split())
- x = pass_date(year, month, date, hour, minute, second, msecond)
- print("Passed date:", x)
- print(x.strftime("Day is %a/%A"))
- add_time = x + timedelta(days=2, hours=3, minutes=15)
- print("After Adding Time:", add_time)
- sub_time = x - timedelta(days=4, hours=6, minutes=23)
- print("After Subtracting Time:", sub_time)
- from datetime import timedelta,datetime
- duration = timedelta(days=3,hours=5,minutes=24)
- print(f"Duration {duration}")
- date1 = datetime(2025,4,10)
- date2 = datetime(2006,3,15)
- diff = date1 - date2
- print("Age is",int(diff.days/365))
- dates = [
- datetime(2025,4,23),
- datetime(2023,7,3),
- datetime(2027,9,13),
- datetime(2022,1,23),
- datetime(2025,5,23)
- ]
- dates.sort()
- for d in dates:
- print(d.strftime("%Y-%m-%d"))
- date_strings = ["2025-03-15","2024-06-10","2023-02-23","2022-09-29"]
- date_objects = []
- for i in date_strings:
- date_objects.append(datetime.strptime(i,"%Y-%m-%d"))
- date_objects.sort()
- for d in date_objects:
- print(d.strftime("%Y-%m-%d"))
- import calendar
- year=int(input("Enter year:"))
- month=int(input("Enter month:"))
- print(calendar.month(year,month))
- import calendar
- year=int(input("Enter year:"))
- print(calendar.calendar(year))
- import calendar
- year,month,day = 2006,3,15
- weekday = calendar.weekday(year,month,day)
- print(weekday)
- from datetime import datetime, timedelta
- date = datetime.now()
- print(date.strftime("%Y-%m-%d %H:%M:%S"))
- print(date.strftime("%A, %B %d, %Y"))
- print(date.strftime("%H:%M %p"))
- print(date.strftime("%d/%m/%Y"))
- cdate = datetime.now()
- print("Complete Date:",cdate)
- print("Year:",cdate.year)
- print("Month Name:",cdate.strftime("%B"))
- print("Day of the Week:",cdate.strftime("%A"))
- print("Hour in 12-Hour Format:",cdate.strftime("%I"))
- print("AM/PM Indicator:",cdate.strftime("%p"))
- #Experiment 6
- import time
- def sleep_pause(t):
- print(f"Program will pause for {t} sec...")
- time.sleep(t)
- print("Execution resumed")
- def input_pause():
- input("Press Enter key to continue:")
- print("Execution resumed")
- def rand_pause():
- import random
- delay = random.randint(2,6)
- print(f"Pausing execution for {delay} sec...")
- time.sleep(delay)
- print("Execution resumed")
- while True:
- print("Choose an option:")
- print("1. Pause for t=3 seconds")
- print("2. Pause until interaction")
- print("3. Pause for random 2-6 sec...")
- print("4. Exit")
- choice = int(input("Enter your choice:"))
- while choice!=4:
- if (choice==1):
- sleep_pause(3)
- break
- elif (choice==2):
- input_pause()
- break
- elif (choice==3):
- rand_pause()
- break
- else:
- print("Wrong input choice!")
- break
- if (choice==4):
- print("Exiting")
- break
- #Experiment 7
- import sqlite3
- def connect_db():
- db = sqlite3.connect("demodb.db")
- print("Database connected")
- return db
- def create_table(db):
- cursor = db.cursor()
- cursor.execute("create table if not exists users(id integer primary key,name text,age integer)")
- print("Table created")
- db.commit()
- def insert_data(db,id,name,age):
- cursor = db.cursor()
- cursor.execute("insert into users(id,name,age) values(?,?,?)",(id,name,age))
- print("\nData inserted into table")
- db.commit()
- def fetch_data(db):
- cursor = db.cursor()
- cursor.execute("select * from users")
- rows = cursor.fetchall()
- print("Fetching...")
- for i in rows:
- print(i)
- db.commit()
- def update_data(db,id,age):
- cursor = db.cursor()
- cursor.execute("update users set age=? where id=?",(age,id))
- print("\nTable updated")
- db.commit()
- def delete_data(db,id):
- cursor = db.cursor()
- cursor.execute("delete from users where id=?",(id,))
- print("\nData deleted")
- db.commit()
- if __name__=="__main__":
- db = connect_db()
- create_table(db)
- insert_data(db,1,"Talha",19)
- insert_data(db,2,"Oubed",16)
- fetch_data(db)
- update_data(db,2,17)
- fetch_data(db)
- delete_data(db,2)
- fetch_data(db)
- db.close()
- print("Database disconnected")
- #Experiment 8
- import sqlite3
- def connect_db():
- db = sqlite3.connect("studentdb.db")
- print("Database connected")
- return db
- def create_table(db):
- cursor = db.cursor()
- cursor.execute("create table if not exists student(name text,usn text primary key,sem integer,marks integer)")
- print("Table created")
- db.commit()
- def insert_data(db,name,usn,sem,marks):
- cursor = db.cursor()
- cursor.execute("insert into student(name,usn,sem,marks) values(?,?,?,?)",(name,usn,sem,marks))
- db.commit()
- def fetch_data(db):
- cursor = db.cursor()
- # cursor.execute("select * from users")
- # rows = cursor.fetchall()
- print("Fetching Data...")
- for i in cursor.execute("select * from student"):
- print(i)
- db.commit()
- def update_data(db,usn,marks):
- cursor = db.cursor()
- cursor.execute("update student set marks=? where usn=?",(marks,usn))
- print("\nTable updated")
- db.commit()
- def delete_data(db,usn):
- cursor = db.cursor()
- cursor.execute("delete from student where usn=?",(usn,))
- print("\n1 Data deleted")
- db.commit()
- def drop_table(db):
- cursor = db.cursor()
- cursor.execute("drop table student")
- print("\nTable dropped")
- db.commit()
- def marks_display(db,marks):
- cursor = db.cursor()
- print("\nFetching custom data...")
- for i in cursor.execute("select * from student where marks>?",(marks,)):
- print(i)
- db.commit()
- if __name__=="__main__":
- db = connect_db()
- create_table(db)
- insert_data(db,"Talha","1NH23AI006",4,45)
- insert_data(db,"Aneesh","1NH23AI017",4,40)
- insert_data(db,"Rohith","1NH23AI001",4,20)
- insert_data(db,"Anil","1NH23AI019",4,30)
- print("\nAll Data inserted")
- fetch_data(db)
- update_data(db,"1NH23AI001",23)
- fetch_data(db)
- delete_data(db,"1NH23AI019")
- fetch_data(db)
- marks_display(db,25)
- drop_table(db)
- db.close()
- print("Database disconnected")
- #Experiment 9
- def divide_numbers(a,b):
- try:
- result=a/b
- return result
- except ZeroDivisionError:
- print("Error: Division by zero is not allowed.")
- return None
- except TypeError:
- print("Error: Invalid data type. Please enter only numbers.")
- return None
- finally:
- print("Execution of divide_numbers() completed.")
- def access_list_element(lst,index):
- try:
- return lst[index]
- except IndexError:
- print(f"Error: Index {index} out of range.")
- return None
- def convert_to_int(value):
- try:
- return int(value)
- except ValueError:
- print(f'Error: Could not convert {value} to an integer.')
- return None
- def ExElseBlock(value):
- try:
- num = int(value)
- except ValueError:
- print("Conversion failed.")
- else:
- print(f'Conversion Successful: {num}')
- finally:
- print("Execution of ExElseBlock completed.")
- if __name__ == "__main__":
- print("--- Handling ZeroDivisionError ---")
- divide_numbers(10,0)
- print("\n--- Handling TypeError ---")
- divide_numbers(10,"two")
- print("\n--- Division without any error ---")
- print(divide_numbers(10,2))
- print("\n--- Handling IndexError ---")
- my_list = [1,2,3]
- access_list_element(my_list,5)
- print("\n--- Handling ValueError ---")
- convert_to_int("abc")
- print("\n--- No ValueError ---")
- print(convert_to_int(34.78))
- print("\n--- Handling Exception with else block ---")
- ExElseBlock("100")
- print("\n--- Handling Exception with else block ---")
- ExElseBlock("abc")
- #Experiment 10
- import tkinter as tk
- from tkinter import messagebox
- def on_button_click():
- messagebox.showinfo("Button Clicked", "You clicked the button!")
- def on_key_press(event):
- label_event.config(text=f'Key Pressed: {event.char}', fg='red')
- def change_color():
- label_color.config(fg='green')
- root = tk.Tk()
- root.title("GUI Demo - Fonts, Colors, Layouts, Events")
- root.geometry("500x400")
- label1 = tk.Label(root, text="Pack Layout Example", font=("Arial", 14, "bold"), fg="blue")
- label1.pack(pady=10)
- frame_grid = tk.Frame(root)
- frame_grid.pack(pady=10)
- label_grid = tk.Label(frame_grid, text="Grid Layout:", font=("Times New Roman",12))
- label_grid.grid(row=0, column=0, padx=5)
- entry_grid = tk.Entry(frame_grid, font=("Verdana",12))
- entry_grid.grid(row=0, column=1, padx=5)
- label_place = tk.Label(root, text="Place Layout Example", font=("Comic Sans MS",12), fg="purple")
- label_place.place(x=180, y=120)
- label_place.pack(pady=10)
- button_event = tk.Button(root, text="Click Me!", font=("Courier",12,"bold"), bg="yellow", command=on_button_click)
- button_event.pack(pady=10)
- label_color = tk.Label(root, text="Change My Color", font=("Helvetica", 14))
- label_color.pack()
- button_color = tk.Button(root, text="Change Color", command=change_color)
- button_color.pack(pady=5)
- label_event = tk.Label(root, text="Press Any Key", font=("Arial",12), fg="black")
- label_event.pack(pady=10)
- root.bind("<KeyPress>", on_key_press)
- root.mainloop()
- #Experiment 11
- #Server side: first run this in new notebook
- import socket
- server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- server_socket.bind(("localhost",123))
- server_socket.listen(1)
- print("Server is waiting for a connection...")
- client_socket, addr = server_socket.accept()
- print(f"Connected to {addr}")
- client_socket.send("Hello, Client! Type 'bye' to exit.".encode())
- while True:
- data = client_socket.recv(1024).decode()
- if data.lower() == "bye":
- print("Client disconnected")
- break
- print(f"Client: {data}")
- response = input("Server: ")
- client_socket.send(response.encode())
- client_socket.close()
- server_socket.close()
- #Client side: then run this in other notebook
- import socket
- client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- client_socket.connect(("localhost",123))
- print("Connected to server")
- message = client_socket.recv(1024).decode()
- print("Server:",message)
- while True:
- msg = input("Client: ")
- client_socket.send(msg.encode())
- if msg.lower() == "bye":
- print("Disconnected from server")
- break
- response = client_socket.recv(1024).decode()
- print("Server:",response)
- client_socket.close()
- #Experiment 12
- class Employee:
- def __init__(self,name):
- self.name = name
- def printName(self):
- print(self.name)
- obj = Employee("ABU")
- obj.printName()
- del obj
- #obj.printName()
- #Experiment 13
- class Student:
- college_name = "NHCE"
- def __init__(self, name, age):
- self.name = name
- self.age = age
- # Instance Method
- def display(self):
- print(f"Student name : {self.name}, Age : {self.age}")
- @classmethod
- def change_college(cls, new_name):
- cls.college_name = new_name
- @staticmethod
- def welcome_message():
- print("Welcome to the Student Management System")
- # Inheritance in Python
- class Person:
- def __init__(self, name, age):
- self.name = name
- self.age = age
- def show_details(self):
- print(f"Name: {self.name}, Age: {self.age}")
- # Child class inheriting from Person
- class Employee(Person):
- def __init__(self, name, age, salary):
- super().__init__(name, age)
- self.salary = salary
- def show_details(self):
- super().show_details() # Calling parent method
- print(f"Salary: {self.salary}")
- class Cat:
- def sound(self):
- return "Meow"
- class Dog:
- def sound(self):
- return "Bark"
- # Function demonstrating polymorphism
- def make_sound(animal):
- print(animal.sound())
- # Demonstrating Types of Methods
- s1 = Student("Alice", 20)
- s1.display() # Instance Method
- Student.welcome_message() # Static Method
- Student.change_college("New Horizon College Of Engineering") # Class method
- print("Updated College Name:", Student.college_name)
- # Demonstrating Inheritance
- emp1 = Employee("John", 30, 50000)
- emp1.show_details()
- # Demonstrating Polymorphism
- cat = Cat()
- dog = Dog()
- make_sound(cat)
- make_sound(dog)
- #Experiment 14
- from abc import ABC, abstractmethod
- class Animal(ABC):
- def sound(self):
- pass
- def common_behavior(self):
- print("All animals need food and water")
- class Dog(Animal):
- def sound(self):
- return "Bark"
- class Cat(Animal):
- def sound(self):
- return "Meow"
- dog = Dog()
- cat = Cat()
- print(f"Dog says: {dog.sound()}")
- print(f"Cat says: {cat.sound()}")
- class Vehicle(ABC):
- @abstractmethod
- def start_engine(self):
- pass
- def stop_engine(self):
- pass
- class Car(Vehicle):
- def start_engine(self):
- print("Car engine started")
- def stop_engine(self):
- print("Car engine stopped")
- class Bike(Vehicle):
- def start_engine(self):
- print("Bike engine started")
- def stop_engine(self):
- print("Bike engine stopped")
- car = Car()
- bike = Bike()
- car.start_engine()
- car.stop_engine()
- bike.start_engine()
- bike.stop_engine()
- from abc import ABC, abstractmethod
- class Shape(ABC):
- @abstractmethod
- def area(self):
- pass
- class Square(Shape):
- def __init__(self, side_length):
- self.side_length = side_length
- def area(self):
- return self.side_length ** 2
- class Rectangle(Shape):
- def __init__(self, width, height):
- self.width = width
- self.height = height
- def area(self):
- return self.width * self.height
- square = Square(4)
- rectangle = Rectangle(4, 6)
- print(f"Area of Square: {square.area()}")
- print(f"Area of Rectangle: {rectangle.area()}")
- #Experiment 15
- class Student():
- def __init__(self,name,rollno,street,city,pincode):
- self.name = name
- self.rollno = rollno
- self.address = self.Address(street,city,pincode)
- def display(self):
- print("Student Name:",self.name)
- print("Student Roll No:",self.rollno)
- self.address.display()
- class Address():
- def __init__(self,street,city,pincode):
- self.street = street
- self.city = city
- self.pincode = pincode
- def display(self):
- print(f"Address: {self.street}, {self.city} - {self.pincode}")
- std1 = Student("Abu",101,7,"Bangalore",560001)
- std1.display()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement