Advertisement
GamerBhai02

APP ALL CODES

May 29th, 2025 (edited)
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 21.76 KB | Source Code | 0 0
  1. #Experiment 1
  2.     import os
  3.     file = open('demo.txt','w')
  4.     file.write("Hello World!")
  5.     file.close()
  6.     file = open('demo.txt','r')
  7.     print(file.read())
  8.     file.close()
  9.  
  10.     with open('demo.txt','a') as file:
  11.         file.write("\nHave a good day")
  12.     with open('demo.txt','r') as file:
  13.         print(file.read())
  14.  
  15.     with open('demo.txt','r') as file:
  16.         file.seek(6)
  17.         print(file.tell())
  18.         content = file.read()
  19.         print(content)
  20.         print(file.tell())
  21.  
  22.     import os
  23.     file = open('demo.bin','wb')
  24.     file.write(b"Hello World!")
  25.     file.close()
  26.     file = open('demo.bin','rb')
  27.     print(file.read())
  28.     file.close()
  29.  
  30.     with open('demo.bin','ab') as file:
  31.         file.write(b"\nHave a good day")
  32.     with open('demo.bin','rb') as file:
  33.         print(file.read())
  34.  
  35.     with open('demo.bin','rb') as file:
  36.         file.seek(6)
  37.         print(file.tell())
  38.         content = file.read()
  39.         print(content)
  40.         print(file.tell())
  41.  
  42.     import zipfile
  43.     with zipfile.ZipFile("zipped_files.zip",'w') as zipf:
  44.         zipf.write("demo.txt")
  45.         zipf.write("demo.bin")
  46.         print("Files Zipped Successfully")
  47.  
  48.     with zipfile.ZipFile("zipped_files.zip",'r') as zipf:
  49.         zipf.extractall("unzipped_files")
  50.         print("Files Unzipped Successfully")
  51.  
  52.     if os.path.exists('demo.txt'):
  53.         os.remove('demo.txt')
  54.         print("File Deleted")
  55.     else:
  56.         print("File doesn't exist")
  57.  
  58.     if os.path.exists('demo.bin'):
  59.         os.remove('demo.bin')
  60.         print("File Deleted")
  61.     else:
  62.         print("File doesn't exist")
  63.  
  64. import os
  65. with open('std_records.txt','w') as file:
  66.     file.write('Student Name,Roll Number,Student Marks\n')
  67.     file.write('John,1001,98\n')
  68.     file.write('Ben,1002,84\n')
  69.     file.write('Tom,1003,91\n')
  70.     file.write('Adam,1004,76\n')
  71.     file.write('Tim,1005,89')
  72.     print("Records Inserted Successfully")
  73.  
  74.  
  75. # In[31]:
  76.  
  77.  
  78. if os.path.exists('std_records.txt'):
  79.     with open('std_records.txt','r') as file:
  80.         print(file.read())
  81. else:
  82.     print("Student Records Doesnt Exist")
  83.  
  84.  
  85. # In[32]:
  86.  
  87.  
  88. if os.path.exists('std_records.txt'):
  89.     roll_number = input("Enter Student Roll Number:")
  90.     with open('std_records.txt', 'r') as file:
  91.         header = file.readline()
  92.         found = False
  93.         for line in file:
  94.             if roll_number in line:
  95.                 print(f"Record Found:\n{header}{line.strip()}")
  96.                 found = True
  97.                 break
  98.         if not found:
  99.             print("Record not found.")
  100. else:
  101.     print("Student Records Doesnt Exist")
  102.  
  103.  
  104. # In[33]:
  105.  
  106.  
  107. with open('C:\\Users\\Student\\Pictures\\sampleimg.jpg','rb') as img:
  108.     imagedata = img.read()
  109.  
  110.  
  111. # In[34]:
  112.  
  113.  
  114. from PIL import Image
  115. import matplotlib.pyplot as plt
  116. with open('output_image.jpg','wb') as img:
  117.     image = img.write(imagedata)
  118. image = Image.open('output_image.jpg')
  119. plt.imshow(image)
  120. plt.axis("off")
  121. plt.show()
  122.  
  123.  
  124. # In[35]:
  125.  
  126.  
  127. import zipfile
  128. with zipfile.ZipFile("student_zipped.zip",'w') as zipf:
  129.     zipf.write('std_records.txt')
  130.     zipf.write('student_details.bin')
  131.     print("Files Zipped Successfully")
  132.  
  133.  
  134. # In[36]:
  135.  
  136.  
  137. with zipfile.ZipFile("student_zipped.zip",'r') as zipf:
  138.     zipf.extractall("Student Details")
  139.     print("Files Unzipped Successfully")
  140.  
  141.  
  142. #Experiment 2
  143. with open('maildata.txt','r') as file:
  144.     data = file.read()
  145. email_pattern = r'[a-zA-Z0-9.!$%-]+@[a-zA-Z0-9-]+\.[a-zA-Z]{2,}'
  146. emails = re.findall(email_pattern, data)
  147. for email in emails:
  148.     print(email)
  149.  
  150. with open('phdata.txt','r') as file:
  151.     data = file.read()
  152. pattern = r'\+?\(?(\d{1,3})?\)?[\s\-]?\(?(\d{3})\)?[\s\-]?(\d{3})[\s\-]?(\d{4})'
  153. phnos = re.findall(pattern,data)
  154. print(phnos)
  155. for num in phnos:
  156.     print(''.join(num))
  157. import re
  158. file_path = "demodata.txt"
  159. with open(file_path, 'r') as file:
  160.     content = file.read()
  161. hashtags = re.findall(r"#\w+", content)
  162. print("Extracted Hashtags:", hashtags)
  163.  
  164.  
  165. #Experiment 3
  166. with open('demo1.html','r') as file:
  167.     data = file.read()
  168.  
  169. title_pattern = r'<title>(.*)?</title>'
  170. titles = re.findall(title_pattern,data,re.IGNORECASE)
  171. print(f'Title: {titles}')
  172.  
  173. head_pattern = r'<h[1-6]>(.*)?</h[1-6]>'
  174. heads = re.findall(head_pattern,data,re.IGNORECASE)
  175. print(f'Heading: {heads}')
  176.  
  177. p_pattern = r'<p>(.*)?</p>'
  178. ps = re.findall(p_pattern,data,re.IGNORECASE)
  179. print(f'Paras: {ps}')
  180.  
  181. link_pattern = r'<a\s+href=["\'](.*)?["\']>'
  182. links = re.findall(link_pattern,data,re.IGNORECASE)
  183. print(f'Links: {links}')  
  184.  
  185.  
  186. #Experiment 4
  187. import threading as t
  188. def square(num):
  189.     print(f"Square of {num} is {num**2}")
  190. def cube(num):
  191.     print(f"Cube of {num} is {num**3}")
  192. number = int(input("Enter a number to find square and cube:"))
  193. thread1 = t.Thread(target=square,args=(number,))
  194. thread2 = t.Thread(target=cube,args=(number,))
  195. thread1.start()
  196. thread2.start()
  197. thread1.join()
  198. thread2.join()
  199. print("Both threads have executed successfully")
  200.  
  201.  
  202. import threading as t
  203. import time
  204. def print_numbers():
  205.     for i in range(1,6):
  206.         print(f"Number: {i}")
  207.         time.sleep(1)
  208. def print_alphabets():
  209.     for char in 'ABCDE':
  210.         print(f"Alphabet: {char}")
  211.         time.sleep(1)
  212. thread1 = t.Thread(target=print_numbers)
  213. thread2 = t.Thread(target=print_alphabets)
  214. thread1.start()
  215. thread2.start()
  216. thread1.join()
  217. thread2.join()
  218.  
  219. print("Both threads have executed successfully")
  220.  
  221.  
  222.  
  223. #Experiment 5
  224. from datetime import datetime
  225. import time
  226.  
  227. def show_current_time():
  228.     now = datetime.now()
  229.     print("Current Date and Time:",now.strftime("%Y-%m-%d %H:%M:%S"))
  230. def set_alarm(hour,minute):
  231.     print(f"Alarm set for {hour}:{minute}. Waiting to ring...")
  232.     while True:
  233.         now = datetime.now()
  234.         if now.hour == hour and now.minute == minute:
  235.             print("It is time to wake up!!")
  236.             print("📢📢📢📢📢📢📢📢📢")
  237.             break
  238.         time.sleep(10)
  239. def calc_date_diff(date1,date2):
  240.     d1 = datetime.strptime(date1,"%Y-%m-%d")
  241.     d2 = datetime.strptime(date2,"%Y-%m-%d")
  242.     diff = abs((d2-d1).days)
  243.     print(f"The difference between {date1} and {date2} is {diff} days.")
  244.  
  245. print("Date and Time Application")
  246. while True:
  247.     print("1. Show Current Date & Time")
  248.     print("2. Set an Alarm")
  249.     print("3. Calculate Date Difference")
  250.     print("4. Exit")
  251.     choice = input("Enter your choice:")
  252.     if (choice=='1'):
  253.         show_current_time()
  254.     elif (choice=='2'):
  255.         hour = int(input("Enter hour (24-hour format):"))
  256.         minute = int(input("Enter minute:"))
  257.         set_alarm(hour,minute)
  258.     elif (choice=='3'):
  259.         date1 = input("Enter 1st date (YYYY-MM-DD):")
  260.         date2 = input("Enter 2nd date (YYYY-MM-DD):")
  261.         calc_date_diff(date1,date2)
  262.     elif (choice=='4'):
  263.         print("Exiting")
  264.         break
  265.     else:
  266.         print("Invalid choice. Please try again.")
  267.  
  268. from datetime import datetime, timedelta
  269.  
  270. def pass_date(year, month, date, hour, minute, second, msecond):
  271.     return datetime(year, month, date, hour, minute, second, msecond)
  272.  
  273. 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())
  274. x = pass_date(year, month, date, hour, minute, second, msecond)
  275.  
  276. print("Passed date:", x)
  277. print(x.strftime("Day is %a/%A"))
  278.  
  279. add_time = x + timedelta(days=2, hours=3, minutes=15)
  280. print("After Adding Time:", add_time)
  281.  
  282. sub_time = x - timedelta(days=4, hours=6, minutes=23)
  283. print("After Subtracting Time:", sub_time)
  284.  
  285. from datetime import timedelta,datetime
  286. duration = timedelta(days=3,hours=5,minutes=24)
  287. print(f"Duration {duration}")
  288.  
  289.  
  290. date1 = datetime(2025,4,10)
  291. date2 = datetime(2006,3,15)
  292. diff = date1 - date2
  293. print("Age is",int(diff.days/365))
  294.  
  295. dates = [
  296.     datetime(2025,4,23),
  297.     datetime(2023,7,3),
  298.     datetime(2027,9,13),
  299.     datetime(2022,1,23),
  300.     datetime(2025,5,23)
  301. ]
  302. dates.sort()
  303. for d in dates:
  304.     print(d.strftime("%Y-%m-%d"))
  305.  
  306.  
  307. date_strings = ["2025-03-15","2024-06-10","2023-02-23","2022-09-29"]
  308. date_objects = []
  309. for i in date_strings:
  310.     date_objects.append(datetime.strptime(i,"%Y-%m-%d"))
  311. date_objects.sort()
  312. for d in date_objects:
  313.     print(d.strftime("%Y-%m-%d"))
  314.  
  315.  
  316. import calendar
  317. year=int(input("Enter year:"))
  318. month=int(input("Enter month:"))
  319. print(calendar.month(year,month))
  320.  
  321.  
  322. import calendar
  323. year=int(input("Enter year:"))
  324. print(calendar.calendar(year))
  325.  
  326. import calendar
  327. year,month,day = 2006,3,15
  328. weekday = calendar.weekday(year,month,day)
  329. print(weekday)
  330.  
  331.  
  332. from datetime import datetime, timedelta
  333. date = datetime.now()
  334. print(date.strftime("%Y-%m-%d %H:%M:%S"))
  335. print(date.strftime("%A, %B %d, %Y"))
  336. print(date.strftime("%H:%M %p"))
  337. print(date.strftime("%d/%m/%Y"))
  338.  
  339. cdate = datetime.now()
  340. print("Complete Date:",cdate)
  341. print("Year:",cdate.year)
  342. print("Month Name:",cdate.strftime("%B"))
  343. print("Day of the Week:",cdate.strftime("%A"))
  344. print("Hour in 12-Hour Format:",cdate.strftime("%I"))
  345. print("AM/PM Indicator:",cdate.strftime("%p"))
  346.  
  347.  
  348. #Experiment 6
  349. import time
  350.  
  351. def sleep_pause(t):
  352.     print(f"Program will pause for {t} sec...")
  353.     time.sleep(t)
  354.     print("Execution resumed")
  355. def input_pause():
  356.     input("Press Enter key to continue:")
  357.     print("Execution resumed")
  358. def rand_pause():
  359.     import random
  360.     delay = random.randint(2,6)
  361.     print(f"Pausing execution for {delay} sec...")
  362.     time.sleep(delay)
  363.     print("Execution resumed")
  364.  
  365. while True:
  366.     print("Choose an option:")
  367.     print("1. Pause for t=3 seconds")
  368.     print("2. Pause until interaction")
  369.     print("3. Pause for random 2-6 sec...")
  370.     print("4. Exit")
  371.     choice = int(input("Enter your choice:"))
  372.     while choice!=4:
  373.         if (choice==1):
  374.             sleep_pause(3)
  375.             break
  376.         elif (choice==2):
  377.             input_pause()
  378.             break
  379.         elif (choice==3):
  380.             rand_pause()
  381.             break
  382.         else:
  383.             print("Wrong input choice!")
  384.             break
  385.     if (choice==4):
  386.         print("Exiting")
  387.         break
  388.  
  389.  
  390.  
  391. #Experiment 7
  392. import sqlite3
  393.  
  394. def connect_db():
  395.     db = sqlite3.connect("demodb.db")
  396.     print("Database connected")
  397.     return db
  398.  
  399. def create_table(db):
  400.     cursor = db.cursor()
  401.     cursor.execute("create table if not exists users(id integer primary key,name text,age integer)")
  402.     print("Table created")
  403.     db.commit()
  404.  
  405. def insert_data(db,id,name,age):
  406.     cursor = db.cursor()
  407.     cursor.execute("insert into users(id,name,age) values(?,?,?)",(id,name,age))
  408.     print("\nData inserted into table")
  409.     db.commit()
  410.  
  411. def fetch_data(db):
  412.     cursor = db.cursor()
  413.     cursor.execute("select * from users")
  414.     rows = cursor.fetchall()
  415.     print("Fetching...")
  416.     for i in rows:
  417.         print(i)
  418.     db.commit()
  419.  
  420. def update_data(db,id,age):
  421.     cursor = db.cursor()
  422.     cursor.execute("update users set age=? where id=?",(age,id))
  423.     print("\nTable updated")
  424.     db.commit()
  425.  
  426. def delete_data(db,id):
  427.     cursor = db.cursor()
  428.     cursor.execute("delete from users where id=?",(id,))
  429.     print("\nData deleted")
  430.     db.commit()
  431.  
  432. if __name__=="__main__":
  433.     db = connect_db()
  434.     create_table(db)
  435.     insert_data(db,1,"Talha",19)
  436.     insert_data(db,2,"Oubed",16)
  437.     fetch_data(db)
  438.     update_data(db,2,17)
  439.     fetch_data(db)
  440.     delete_data(db,2)
  441.     fetch_data(db)
  442.     db.close()
  443.     print("Database disconnected")
  444.  
  445.  
  446.  
  447. #Experiment 8
  448. import sqlite3
  449.  
  450. def connect_db():
  451.     db = sqlite3.connect("studentdb.db")
  452.     print("Database connected")
  453.     return db
  454.  
  455. def create_table(db):
  456.     cursor = db.cursor()
  457.     cursor.execute("create table if not exists student(name text,usn text primary key,sem integer,marks integer)")
  458.     print("Table created")
  459.     db.commit()
  460.  
  461. def insert_data(db,name,usn,sem,marks):
  462.     cursor = db.cursor()
  463.     cursor.execute("insert into student(name,usn,sem,marks) values(?,?,?,?)",(name,usn,sem,marks))
  464.     db.commit()
  465.  
  466. def fetch_data(db):
  467.     cursor = db.cursor()
  468.     # cursor.execute("select * from users")
  469.     # rows = cursor.fetchall()
  470.     print("Fetching Data...")
  471.     for i in cursor.execute("select * from student"):
  472.         print(i)
  473.     db.commit()
  474.  
  475. def update_data(db,usn,marks):
  476.     cursor = db.cursor()
  477.     cursor.execute("update student set marks=? where usn=?",(marks,usn))
  478.     print("\nTable updated")
  479.     db.commit()
  480.  
  481. def delete_data(db,usn):
  482.     cursor = db.cursor()
  483.     cursor.execute("delete from student where usn=?",(usn,))
  484.     print("\n1 Data deleted")
  485.     db.commit()
  486.  
  487. def drop_table(db):
  488.     cursor = db.cursor()
  489.     cursor.execute("drop table student")
  490.     print("\nTable dropped")
  491.     db.commit()
  492.    
  493. def marks_display(db,marks):
  494.     cursor = db.cursor()
  495.     print("\nFetching custom data...")
  496.     for i in cursor.execute("select * from student where marks>?",(marks,)):
  497.         print(i)
  498.     db.commit()
  499.  
  500. if __name__=="__main__":
  501.     db = connect_db()
  502.     create_table(db)
  503.     insert_data(db,"Talha","1NH23AI006",4,45)
  504.     insert_data(db,"Aneesh","1NH23AI017",4,40)
  505.     insert_data(db,"Rohith","1NH23AI001",4,20)
  506.     insert_data(db,"Anil","1NH23AI019",4,30)
  507.     print("\nAll Data inserted")
  508.     fetch_data(db)
  509.     update_data(db,"1NH23AI001",23)
  510.     fetch_data(db)
  511.     delete_data(db,"1NH23AI019")
  512.     fetch_data(db)
  513.     marks_display(db,25)
  514.     drop_table(db)
  515.     db.close()
  516.     print("Database disconnected")
  517.  
  518.  
  519.  
  520.  
  521. #Experiment 9
  522. def divide_numbers(a,b):
  523.     try:
  524.         result=a/b
  525.         return result
  526.     except ZeroDivisionError:
  527.         print("Error: Division by zero is not allowed.")
  528.         return None
  529.     except TypeError:
  530.         print("Error: Invalid data type. Please enter only numbers.")
  531.         return None
  532.     finally:
  533.         print("Execution of divide_numbers() completed.")
  534.        
  535. def access_list_element(lst,index):
  536.     try:
  537.         return lst[index]
  538.     except IndexError:
  539.         print(f"Error: Index {index} out of range.")
  540.         return None
  541.  
  542. def convert_to_int(value):
  543.     try:
  544.         return int(value)
  545.     except ValueError:
  546.         print(f'Error: Could not convert {value} to an integer.')
  547.         return None
  548.  
  549. def ExElseBlock(value):
  550.     try:
  551.         num = int(value)
  552.     except ValueError:
  553.         print("Conversion failed.")
  554.     else:
  555.         print(f'Conversion Successful: {num}')
  556.     finally:
  557.         print("Execution of ExElseBlock completed.")
  558.        
  559. if __name__ == "__main__":
  560.     print("--- Handling ZeroDivisionError ---")
  561.     divide_numbers(10,0)
  562.    
  563.     print("\n--- Handling TypeError ---")
  564.     divide_numbers(10,"two")
  565.    
  566.     print("\n--- Division without any error ---")
  567.     print(divide_numbers(10,2))
  568.    
  569.     print("\n--- Handling IndexError ---")
  570.     my_list = [1,2,3]
  571.     access_list_element(my_list,5)
  572.    
  573.     print("\n--- Handling ValueError ---")
  574.     convert_to_int("abc")
  575.    
  576.     print("\n--- No ValueError ---")
  577.     print(convert_to_int(34.78))
  578.    
  579.     print("\n--- Handling Exception with else block ---")
  580.     ExElseBlock("100")
  581.    
  582.     print("\n--- Handling Exception with else block ---")
  583.     ExElseBlock("abc")
  584.  
  585.  
  586.  
  587.  
  588. #Experiment 10
  589. import tkinter as tk
  590. from tkinter import messagebox
  591.  
  592. def on_button_click():
  593.     messagebox.showinfo("Button Clicked", "You clicked the button!")
  594.  
  595. def on_key_press(event):
  596.     label_event.config(text=f'Key Pressed: {event.char}', fg='red')
  597.    
  598. def change_color():
  599.     label_color.config(fg='green')
  600.    
  601. root = tk.Tk()
  602. root.title("GUI Demo - Fonts, Colors, Layouts, Events")
  603. root.geometry("500x400")
  604.  
  605. label1 = tk.Label(root, text="Pack Layout Example", font=("Arial", 14, "bold"), fg="blue")
  606. label1.pack(pady=10)
  607.  
  608. frame_grid = tk.Frame(root)
  609. frame_grid.pack(pady=10)
  610.  
  611. label_grid = tk.Label(frame_grid, text="Grid Layout:", font=("Times New Roman",12))
  612. label_grid.grid(row=0, column=0, padx=5)
  613.  
  614. entry_grid = tk.Entry(frame_grid, font=("Verdana",12))
  615. entry_grid.grid(row=0, column=1, padx=5)
  616.  
  617. label_place = tk.Label(root, text="Place Layout Example", font=("Comic Sans MS",12), fg="purple")
  618. label_place.place(x=180, y=120)
  619. label_place.pack(pady=10)
  620.  
  621. button_event = tk.Button(root, text="Click Me!", font=("Courier",12,"bold"), bg="yellow", command=on_button_click)
  622. button_event.pack(pady=10)
  623.  
  624. label_color = tk.Label(root, text="Change My Color", font=("Helvetica", 14))
  625. label_color.pack()
  626. button_color = tk.Button(root, text="Change Color", command=change_color)
  627. button_color.pack(pady=5)
  628.  
  629. label_event = tk.Label(root, text="Press Any Key", font=("Arial",12), fg="black")
  630. label_event.pack(pady=10)
  631. root.bind("<KeyPress>", on_key_press)
  632.  
  633. root.mainloop()
  634.  
  635.  
  636.  
  637.  
  638. #Experiment 11
  639. #Server side: first run this in new notebook
  640. import socket
  641. server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  642. server_socket.bind(("localhost",123))
  643. server_socket.listen(1)
  644. print("Server is waiting for a connection...")
  645. client_socket, addr = server_socket.accept()
  646. print(f"Connected to {addr}")
  647. client_socket.send("Hello, Client! Type 'bye' to exit.".encode())
  648. while True:
  649.     data = client_socket.recv(1024).decode()
  650.     if data.lower() == "bye":
  651.         print("Client disconnected")
  652.         break
  653.     print(f"Client: {data}")
  654.     response = input("Server: ")
  655.     client_socket.send(response.encode())
  656. client_socket.close()
  657. server_socket.close()
  658.  
  659. #Client side: then run this in other notebook
  660. import socket
  661. client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  662. client_socket.connect(("localhost",123))
  663. print("Connected to server")
  664. message = client_socket.recv(1024).decode()
  665. print("Server:",message)
  666. while True:
  667.     msg = input("Client: ")
  668.     client_socket.send(msg.encode())
  669.     if msg.lower() == "bye":
  670.         print("Disconnected from server")
  671.         break
  672.     response = client_socket.recv(1024).decode()
  673.     print("Server:",response)
  674. client_socket.close()
  675.  
  676.  
  677.  
  678. #Experiment 12
  679. class Employee:
  680.     def __init__(self,name):
  681.         self.name = name
  682.     def printName(self):
  683.         print(self.name)
  684.  
  685. obj = Employee("ABU")
  686. obj.printName()
  687. del obj
  688. #obj.printName()
  689.  
  690.  
  691. #Experiment 13
  692. class Student:
  693.     college_name = "NHCE"
  694.     def __init__(self, name, age):
  695.         self.name = name
  696.         self.age = age
  697.     # Instance Method
  698.     def display(self):
  699.         print(f"Student name : {self.name}, Age : {self.age}")
  700.     @classmethod
  701.     def change_college(cls, new_name):
  702.         cls.college_name = new_name
  703.     @staticmethod
  704.     def welcome_message():
  705.         print("Welcome to the Student Management System")
  706.  
  707. # Inheritance in Python
  708. class Person:
  709.     def __init__(self, name, age):
  710.         self.name = name
  711.         self.age = age
  712.     def show_details(self):
  713.         print(f"Name: {self.name}, Age: {self.age}")
  714. # Child class inheriting from Person
  715. class Employee(Person):
  716.     def __init__(self, name, age, salary):
  717.         super().__init__(name, age)
  718.         self.salary = salary
  719.     def show_details(self):
  720.         super().show_details()  # Calling parent method
  721.         print(f"Salary: {self.salary}")
  722.  
  723. class Cat:
  724.     def sound(self):
  725.         return "Meow"
  726. class Dog:
  727.     def sound(self):
  728.         return "Bark"
  729. # Function demonstrating polymorphism
  730. def make_sound(animal):
  731.     print(animal.sound())
  732.  
  733. # Demonstrating Types of Methods
  734. s1 = Student("Alice", 20)
  735. s1.display()  # Instance Method
  736. Student.welcome_message()  # Static Method
  737. Student.change_college("New Horizon College Of Engineering")  # Class method
  738. print("Updated College Name:", Student.college_name)
  739.  
  740. # Demonstrating Inheritance
  741. emp1 = Employee("John", 30, 50000)
  742. emp1.show_details()
  743.  
  744. # Demonstrating Polymorphism
  745. cat = Cat()
  746. dog = Dog()
  747. make_sound(cat)
  748. make_sound(dog)
  749.  
  750.  
  751. #Experiment 14
  752. from abc import ABC, abstractmethod
  753. class Animal(ABC):
  754.     def sound(self):
  755.         pass
  756.     def common_behavior(self):
  757.         print("All animals need food and water")
  758. class Dog(Animal):
  759.     def sound(self):
  760.         return "Bark"
  761. class Cat(Animal):
  762.     def sound(self):
  763.         return "Meow"
  764. dog = Dog()
  765. cat = Cat()
  766. print(f"Dog says: {dog.sound()}")
  767. print(f"Cat says: {cat.sound()}")
  768. class Vehicle(ABC):
  769.     @abstractmethod
  770.     def start_engine(self):
  771.         pass
  772.     def stop_engine(self):
  773.         pass
  774. class Car(Vehicle):
  775.     def start_engine(self):
  776.         print("Car engine started")
  777.     def stop_engine(self):
  778.         print("Car engine stopped")
  779. class Bike(Vehicle):
  780.     def start_engine(self):
  781.         print("Bike engine started")
  782.     def stop_engine(self):
  783.         print("Bike engine stopped")
  784. car = Car()
  785. bike = Bike()
  786. car.start_engine()
  787. car.stop_engine()
  788. bike.start_engine()
  789. bike.stop_engine()
  790. from abc import ABC, abstractmethod
  791. class Shape(ABC):
  792.     @abstractmethod
  793.     def area(self):
  794.         pass
  795. class Square(Shape):
  796.     def __init__(self, side_length):
  797.         self.side_length = side_length
  798.     def area(self):
  799.         return self.side_length ** 2
  800. class Rectangle(Shape):
  801.     def __init__(self, width, height):
  802.         self.width = width
  803.         self.height = height
  804.     def area(self):
  805.         return self.width * self.height
  806. square = Square(4)
  807. rectangle = Rectangle(4, 6)
  808. print(f"Area of Square: {square.area()}")
  809. print(f"Area of Rectangle: {rectangle.area()}")
  810.  
  811.  
  812. #Experiment 15
  813. class Student():
  814.     def __init__(self,name,rollno,street,city,pincode):
  815.         self.name = name
  816.         self.rollno = rollno
  817.         self.address = self.Address(street,city,pincode)
  818.     def display(self):
  819.         print("Student Name:",self.name)
  820.         print("Student Roll No:",self.rollno)
  821.         self.address.display()
  822.     class Address():
  823.         def __init__(self,street,city,pincode):
  824.             self.street = street
  825.             self.city = city
  826.             self.pincode = pincode
  827.         def display(self):
  828.             print(f"Address: {self.street}, {self.city} - {self.pincode}")
  829. std1 = Student("Abu",101,7,"Bangalore",560001)
  830. std1.display()
Tags: Python Exam
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement