0% found this document useful (0 votes)
8 views14 pages

Advance Python Practical Certificate

Types of Methods in Python: 7.1) Instance Methods: - Bound to a class and its instances - Can access and modify instance attributes and methods - Syntax: def method_name(self, args): 7.2) Class Methods: - Bound to a class, not its instances - Can't access instance attributes directly - Syntax: @classmethod def method_name(cls, args): 7.3) Static Methods: - Not bound to a class or instance - Can't access or modify class/instance attributes - Syntax: @staticmethod def method_name(args): 7.4) Special Methods (Magic Methods): - Methods with double

Uploaded by

MAYURESH KASAR
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views14 pages

Advance Python Practical Certificate

Types of Methods in Python: 7.1) Instance Methods: - Bound to a class and its instances - Can access and modify instance attributes and methods - Syntax: def method_name(self, args): 7.2) Class Methods: - Bound to a class, not its instances - Can't access instance attributes directly - Syntax: @classmethod def method_name(cls, args): 7.3) Static Methods: - Not bound to a class or instance - Can't access or modify class/instance attributes - Syntax: @staticmethod def method_name(args): 7.4) Special Methods (Magic Methods): - Methods with double

Uploaded by

MAYURESH KASAR
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Exam Seat No:

Satish Pradhan Dnyanasadhana College


Thane

Certificate

This is to certify that Mr.:Ayush Madheshiya of FYBSc Computer Science


(Semester-II) Class has successfully completed all the practical work in subject
Advance Python, under the guidance of Prof. Trupti Rongare (subject in
charge) during Year 2021-22 in partial fulfillment of Computer Science
Practical Examination conducted by University of Mumbai.

Subject in charge Head of the Department


Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

Date

Sr.
Index Date Sign
No.
Write a program to Python program to
1 implement various file operations.
Write a Program to demonstrate concept of
2 threading and multitasking in Python.
Write a Python Program to work with
databases in Python to perform operations
such as
3 a. Connecting to database
b. Creating and dropping tables
c. Inserting and updating into
tables.
Write a Python Program to demonstrate
4
different types of exception handing.
Write a GUI Program in Python to design
application that demonstrates
5 a. Different fonts and colours
b. Different Layout Managers
c. Event Handling
Write Python Program to create application
6 which uses date and time in Python.
Write a program to Python program to
implement concepts of OOP such as
7 a. Types of Methods
b. Inheritance
c. Polymorphism
Write a program to Python program to
implement concepts of OOP such as
8 a. Abstract methods and classes
b. Interfaces

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

1. Write a program to Python program to implement various file operations.


1.1) File reading Code:
f = open("[Link]", "r")
print([Link]()) [Link]()
Output:
Hello World, Its an test file
1.2) File Writing Code:
f = open("[Link]", "a")
[Link]("Hello from the other side!!")
[Link]() f =
open("[Link]", "r")
print([Link]())
Output:
Hello from the other side!!
1.3) Creating and deleting file
Code:
import os if [Link]("[Link]"):
[Link]("[Link]") print("The file is
removed") else: print("The file does not exist
creating new file") f = open("[Link]", "x")
[Link]()
Output:
The file is removed

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

[Link] a Program to demonstrate concept of threading and


multitasking in Python.
2.1) Threading Code:
import _thread def
cT(tid):
print("Hello Thread ",tid)
def pT(): s = 0 while
True: s += 1
_thread.start_new_thread(cT,(s,))
if input()=="q":
break
pT()
Output:

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

[Link] a Python Program to work with databases in Python to perform


operations such as
a. Connecting to database
b. Creating and dropping tables
c. Inserting and updating into tables. 3.1) Connecting
to database Code:
import pymysql
db = [Link]("localhost","root","12345","mydb") cursor
= [Link]()
[Link]("SELECT VERSION()")
data = [Link]() print("Database
version: ", data) [Link]

3.2) Creating
and dropping
table Code:
import pymysql
db = [Link]("localhost","root","12345","mydb") cursor
= [Link]()
[Link]("DROP TABLE IF EXISTS STUD")
[Link]("CREATE TABLE STUD(NAME VARCHAR(20),AGE INT, SEX
CHAR(1),INCOME FLOAT)") [Link]

3.3) Inserting
data Code:
import pymysql
db = [Link]("localhost","root","12345","mydb")
cursor = [Link]() try:
[Link]("INSERT INTO STUD VALUES ("RAM",18,"M",19868");)
[Link]()
except:
[Link]()
[Link] 3.4) Updating
data Code:
import pymysql
db = [Link]("localhost","root","12345","mydb")
cursor = [Link]() try:
[Link]("UPDATE STUD NAME="JARLISSON" WHERE INCOME=19868");)
[Link]() except:
[Link]() [Link]

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

4. Write a Python Program to demonstrate different types of exception


handing. Code:
try:
a= int(input("Enter a:"))
b = int(input("Enter
b:"))
c = a/b print("a/b =
%d"%c) except Exception:
print("can't divide by zero")
print(Exception) else:
print("Hi I am else block")

Output:

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

[Link] a GUI Program in Python to design application that


demonstrates
b Different fonts and
colours
c Different Layout
Managers
d Event Handling
5.1) Login form
Code:
from tkinter import * import
tkinter as tk from tkinter import
messagebox def loginCheck():
if [Link]() == "VSatish":
if [Link]() == "12345":
[Link]("Logim","Welcome!!")
else:
[Link]("Logim","Invalid Password!")
win = [Link]() [Link]("400x200")
[Link](bg="yellow") [Link]("Login Form")
name = Label(win, text="UserName: ")
[Link]() nameBox =
Entry(win,bd=4)
[Link]()
Passw = Label(win, text="Password: ")
[Link]()
PassBox = Entry(win,bd=4,show="*") [Link]()
loginBtn = Button(win,text="login", command=loginCheck, bg="black",fg="white")
[Link]() [Link]()
output:

5.2) Simple Calculator Code:

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

from tkinter import *


import tkinter as tk
def res(): selection
= [Link]() t1 =
int([Link]()) t2 =
int([Link]()) if
selection == 1:
result = t1 + t2 elif
selection == 2:
result = t1 - t2 elif
selection == 3:
result = t1 / t2
[Link](text="Result is: "+str(result))
win = [Link]() var = IntVar()
lib1 = Label(win,text="Enter First Number:")
[Link]() txt1 = Entry(win, bd=3)
[Link]()
lib2 = Label(win,text="Enter Second Number:")
[Link]() txt2 = Entry(win, bd=3) [Link]()
label = Label(win, text="Result") [Link]()
r1 = Radiobutton(win,text="Add", variable = var,value = 1,command=res)
[Link]()
r2 = Radiobutton(win,text="Sub", variable = var,value = 2,command=res) [Link]()
r3 = Radiobutton(win,text="Div", variable = var,value = 3,command=res)
[Link]() [Link]() Output:

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

[Link] Python Program to create application which uses date and time in
Python.
Code:
import datetime now =
[Link]()
print ("Current date and time : ") print
([Link]("%Y-%m-%d %H:%M:%S")) Output:

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

[Link] a program to Python program to implement concepts of OOP such


as
a. Types of Methods
b. Inheritance
c. Polymorphism
7.1)Single inheritance Code:
class student(): def __init__(self,
name, rollno): [Link] = name
[Link] = rollno def display(self):
print([Link]) print([Link])
class detl(student): def
__init__(self, name, roll, age, semn):
[Link] = age
[Link] = semn
student.__init__(self, name, roll)
a = detl("Sara", 90,
18, 2) [Link]()
Output:

7.2)Multiple inheritance Code:


class Adhar(): def
__init__(self):
[Link] = 531565351
class Pan(): def
__init__(self):
[Link] = "SJAD221S1AS12"
class Person(Adhar, Pan): def
__init__(self,name): [Link] =
name Adhar.__init__(self)
Pan.__init__(self) def getData(self):
print("Name: ",[Link])
print("Andhar No: ", [Link])
print("Pan No: ", [Link])
ob = Person("Gulzar") [Link]()
Output:

7.3) Multilevel inheritance Code:

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

class Family: def show_family(self):


print("Family:") class Father(Family):
fathername = "" def show_father(self):
print([Link]) class Mother(Family):
mothername = "" def show_mother(self):
print([Link]) class Son(Father,
Mother): def show_parent(self):
print("Father :", [Link])
print("Mother :", [Link]) s1 = Son()
[Link] = "Mark" [Link] =
"Sonia" s1.show_family() s1.show_parent()
Output:

7.4) Hierarchical inheritance


Code: class Details: def __init__(self):
self.__id="" self.__name=""
self.__gender="" def
setData(self,id,name,gender):
self.__id=id self.__name=name
self.__gender=gender def
showData(self): print("Id:
",self.__id)
print("Name: ", self.__name)
print("Gender: ", self.__gender) class
Employee(Details): def __init__(self):
self.__company="" self.__dept="" def
setEmployee(self,id,name,gender,comp,dept):
[Link](id,name,gender)
self.__company=comp
self.__dept=dept def
showEmployee(self):
[Link]() print("Company: ",
self.__company) print("Department: ",
self.__dept) class Doctor(Details): def
__init__(self): self.__hospital=""
self.__dept="" def
setEmployee(self,id,name,gender,hos,dept):
[Link](id,name,gender)
self.__hospital=hos self.__dept=dept def
showEmployee(self):

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

[Link]()
print("Hospital: ", self.__hospital)
print("Department: ", self.__dept) e=Employee()
[Link](1,"Prem Sharma","Male","gmr","excavation")
[Link]()
print("\n") d =
Doctor()
[Link](1, "pankaj", "male", "aiims", "eyes")
[Link]() Output:

7.5) Hybrid inheritance Code:


class University: def __init__(self):
[Link] = "MU" def display(self):
print("The University name is: ",[Link])
class Course(University): def
__init__(self): University.__init__(self)
[Link] = "CS" def display(self):
print("The Course name is: ",[Link])
[Link](self) class
Sem(University): def __init__(self):
[Link] = 2 def display(self):
print("The Sem is: ",[Link]) class
Student(Course, Sem): def __init__(self):
[Link] = "Anshuman" Sem.__init__(self)
Course.__init__(self) def display(self):
print("The Name of the student is: ",[Link])
[Link](self)
[Link](self)
ob = Student() print()
[Link]()
Output:

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

2
Satish Pradhan Dnyanasadhana College, Thane [ A. Y. 2021 – 2022]
Name: Ayush Madheshiya Roll No.: 108
Program: FY [Link]. CS (sem II) Subject: Advance Python (PR)

8. Write a program to Python program to implement concepts of OOP such as


a. Abs
tract methods and
classes
b. Int
erfaces Code:
from abc import ABC, abstractmethod
class Car(ABC): def mileage(self):
pass class
Tesla(Car): def
mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car): def
mileage(self):
print("The mileage is 25kmph ")
class Duster(Car): def
mileage(self):
print("The mileage is 24kmph ")
class Renault(Car): def
mileage(self): print("The
mileage is 27kmph ") t= Tesla ()
[Link]() r
= Renault()
[Link]()
s = Suzuki()
[Link]()
d = Duster()
[Link]()
Output:

Common questions

Powered by AI

The OOP principles in the document are demonstrated using various types of inheritance and polymorphism. Single inheritance is shown with a `student` class extended by `detl`, illustrating how a subclass inherits properties and methods from a parent class. Multiple inheritance is used in the `Person` class, which inherits both `Adhar` and `Pan` classes, allowing access to properties from both base classes. Multilevel inheritance is exhibited through a hierarchy of `Family`, `Father`, `Mother`, and `Son` classes, where properties are inherited through multiple levels. Hybrid inheritance and hierarchical inheritance further show more complex relationships between classes. Polymorphism is demonstrated with method overriding and the use of abstract classes, where different subclasses like `Tesla` and `Renault` provide specific implementations of the `mileage` method inherited from the abstract `Car` class .

The design of an OOP-based Python program helps in organizing code by encapsulating data and behaviors within objects, using classes and instances. As seen in the document, OOP principles such as inheritance and polymorphism allow for code reusability and flexibility. Complex functionalities are implemented using class hierarchies that promote a modular approach, such as multiple levels of inheritance seen in `Family`, `Father`, `Son` classes, and polymorphic behaviors in the `Car` class hierarchy. This approach enhances maintenance and scalability, as functionality can be extended through new classes without altering existing code .

The GUI login form in Python ensures user input validation through a conditional check within the `loginCheck()` function. Upon clicking the login button, the function compares the text in `Entry` widgets for correct username and password. The process uses straightforward conditional statements to verify if the credentials match predefined values. If they do, a success message is displayed; otherwise, an error message is shown using `messagebox.showinfo()`. This approach provides basic validation, ensuring only authorized access via a graphical interface .

In Python, file operations include reading from, writing to, creating, and deleting files. The document illustrates these operations with examples. For reading, `open()` is used in read mode to access file content, while writing uses append ('a') or write ('w') modes to add content to files. Creation of files involves using 'x' mode in `open()`, which will raise an error if the file already exists. Deletion is performed using `os.remove()` after checking existence with `os.path.exists()`. These operations are vital for handling data persistently across session executions .

In Python, date and time handling is facilitated by the `datetime` module, which provides classes for manipulating dates and times in both simple and complex ways. The document shows the use of `datetime.datetime.now()` to get the current date and time, formatted using `strftime()`. This allows conversion of time into readable strings for display or logging purposes. Such functionality is essential for applications needing timestamped logging, scheduling, or monitoring, enhancing operational functionalities through temporal data processing .

The concept of threading and multitasking in Python allows a program to execute multiple operations concurrently, hence improving performance, especially for tasks that are I/O bound or use a lot of external resources. In the provided example, threading is demonstrated using the `_thread` module, where new threads are initiated via the `start_new_thread` method, leading to multiple 'Hello Thread' outputs with unique identifiers. However, Python's Global Interpreter Lock (GIL) can impact performance as it allows only one thread to execute at a time, so proper management of threads is crucial to optimize tasks .

To establish a database connection and perform CRUD operations in Python, import the necessary database module such as `pymysql`, which is used for MySQL databases. First, establish a connection using `pymysql.connect()` with parameters like host, user, password, and database name. Perform operations using a cursor object with methods such as `execute()` for SQL queries. For creating and dropping tables, use `DROP TABLE IF EXISTS` and `CREATE TABLE` statements. Inserting involves the `INSERT INTO` query, and updates use the `UPDATE` query. Use exception handling to manage errors, committing changes with `db.commit()`, and rolling back with `db.rollback()` if needed. Finally, close the connection using `db.close()` to free resources .

The GUI calculator designed using Python's Tkinter module includes various user interface components such as Labels, Entry widgets for user input, and Radiobuttons for operation selection. The main interaction model is event-driven, where the GUI waits for user inputs and button clicks. Upon selection of an arithmetic operation using the Radiobuttons, the `res()` function calculates the result based on inputs from Entry widgets and updates the Label with the computed result. The layout managers and event handling are managed through the geometry and command properties in Tkinter, providing a straightforward interface for a simple calculator .

The Python program in the document handles exceptions using try-except blocks. The logic begins by attempting operations that could raise an exception, such as division where division by zero is possible. The program takes two integer inputs and performs division inside a try block. If an exception occurs, such as a zero division error, the code execution jumps to the except block, where a user-friendly error message is displayed. The else block, which is executed if no exceptions occur, follows the try-except structure. This setup ensures the program gracefully manages runtime errors without crashing .

Abstract methods and classes in Python define a blueprint for other classes. The abstract class `Car` in the document cannot be instantiated directly; it serves as a base for its subclasses, enforcing the subclasses like `Tesla` and `Suzuki` to implement the abstract method `mileage`. This ensures consistent interfaces across subclasses while allowing flexibility in implementation. Abstract classes help organize code and provide a clear structure for derivatives to follow, promoting code reusability and scalability .

You might also like