PYTHON
Classes and Objects
Class contains attributes(variables) and methods(functions).
Object is an instance of a class.
To create a class, use the keyword class:
Syntax:
class classname:
Eg:
class Student
Program to create a class and object
class Demo:
print("hiiiiiii")
d=Demo() # d is object
Output: hiiiiiii
The __init__() Function
All classes have a function called __init__(), which is always executed
when the class is being initiated.
Use the __init__() function to assign values to object properties, or other
operations that are necessary to do when the object is being created
Self parameter
The self parameter is a reference to the current instance of the class, and
is used to access variables that belong to the class.
It does not have to be named self , you can call it whatever you like, but it
has to be the first parameter of any function in the class.
program
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
print("my age is ",[Link])
p1 = Person("Raj", 36)
[Link]()
print(p1)
Output:
Hello my name is Raj
my age is 36
<__main__.Person object at 0x00000207AA122E08>
Modifying and deleting object properties
Object properties can be modified and deleted.
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
print("my age is ",[Link])
p1 = Person("Raj", 36)
[Link]()
[Link] = 40 # modifying object property age
print([Link])
print(p1)
del [Link] # deleting object property age
print([Link]) # encounters error
Output:
AttributeError: 'Person' object has no attribute 'age'
Hello my name is Raj
my age is 36
40
The pass Statement
class definitions cannot be empty.
If class definition has no content, put in the pass statement to avoid
getting an error.
Example:
class Person:
pass
Inheritance
Inheritance allows to define a class that inherits all the methods and
properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.
class Student:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def show(self):
print([Link], [Link])
class Child(Student):
pass
s = Student("Jai", "Joshitha")
[Link]()
c = Child("Kaarthikeya", "Raj")
[Link]()
Output:
Jai Joshitha
Kaarthikeya Raj
Child class having own methods
class Student:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def show(self):
print([Link], [Link])
class Child(Student):
def add(self):
a,b=10,20
s=a+b
print("sum=",s)
s = Student("Jai", "Joshitha")
[Link]()
c = Child("Kaarthikeya", "Raj")
[Link]()
[Link]()
Output:
Jai Joshitha
Kaarthikeya Raj
sum= 30
Method Overriding
If the super class and sub class contains the same method name then the
method in sub class invokes overriding the super class method.
program
class Student:
def __init__(self, name, cname,yname):
[Link] = name
[Link] = cname
[Link] = yname
def show(self):
print([Link], [Link],[Link])
class Child(Student):
marks = array('i', [])
def mark(self):
n=int(input("enter [Link] subjects"))
for i in range(n):
x = int(input("enter marks"))
[Link](x)
def show(self):
print("marks are.....")
for i in [Link]:
print(i)
s = Student("Joshitha","MCA",2)
[Link]()
c = Child("Raj","MBA",1)
[Link]()
[Link]() #method overriding
Output:
Joshitha MCA 2
enter [Link] subjects3
enter marks99
enter marks94
enter marks98
marks are.....
99
94
98
Super()
It invokes the members of super class from sub class.
class Student:
def __init__(self, name, cname,yname):
[Link] = name
[Link] = cname
[Link] = yname
def show(self):
print([Link], [Link],[Link])
class Child(Student):
marks = array('i', [])
def mark(self):
n=int(input("enter [Link] subjects"))
for i in range(n):
x = int(input("enter marks"))
[Link](x)
def show(self):
super().show() #using super to prevent method overriding
print("marks are.....")
for i in [Link]:
print(i)
s = Student("Joshitha","MCA",2)
[Link]()
c = Child("Raj","MBA",1)
[Link]()
[Link]() #method overriding
Output:
Joshitha MCA 2
enter [Link] subjects3
enter marks99
enter marks94
enter marks98
Raj MBA 1
marks are.....
99
94
98
File Handling
Data is very [Link] store data in computer we need [Link] the
data is stored in computer file we can retrieve it and use it depending on
the requirement.
Types of files
1. Text files- Text files store data in form of [Link] cannot
store images.
2. Binary files- Binary files store data in form of [Link] can store
text,images,audio,video.
Opening a file
Open() is used to open a file.
Filehandler=open(“file name” , ”mode”)
There are four different modes for opening a file:
1) "r" (Read)- Opens a file for reading, error if the file does not exist
2) "a" (Append) - Opens a file for appending, creates the file if it does
not exist
3) "w" (Write) - Opens a file for writing, creates the file if it does not
[Link] any data already exists in file ,it is deleted and new data is
stored.
4) "x" (Create) - Creates the specified file, returns an error if the file
exists.
5) "a+" (Append and read) - Opens a file for appending and reading,
creates the file if it does not exist
6) "w+" (Write and read) - Opens a file for writing and reading, creates
the file if it does not [Link] any data already exists in file ,it is
deleted and new data is stored.
7) "r+" (Read and write)-Opens a file for reading and writing, creates
the file if it does not [Link] data already exists in file ,it does not
delete the data and the file pointer is placed at beginning of file
Closing a file
[Link]() is used to close a file
Program to demonstrate file operations
# Reading from existing file
f = open('Demo','r')
print("Reading the file.....")
print([Link]())
[Link]() #closing a file
# Appending data to file
"""f=open('Demo','a')
[Link]("Enjoy the class with fun coding")
f = open('Demo','r')
print("After appending.....")
print([Link]())"""
# writting data to file
"""f=open('Demo','w')
[Link]("All the best")
f = open('Demo','r')
print("After writing.....")
print([Link]())"""
# creating new file
"""f=open('Demo1','x')
[Link]("This is newly created file")
f = open('Demo1','r')
print("new file data.....")
print([Link]())"""
Binary file
For binary file after the mode it is necessary to specify the filetype
Example: To open the binary file xyz in read mode
Open(‘xyz’ , ‘rb’) where r -readmode ,b-binaryfile
Program to demonstrate binary file operations
f1=open('[Link]','rb')
for i in f1:
print(i)
# copying file
"""f1=open('[Link]','rb')
f2=open('[Link]','wb')
b=[Link]()
[Link](b)
f2=open('[Link]','rb')
for i in f2:
print(i)"""
Assertion
An assertion is a debugging aid that tests a boolean condition in your code. If
the condition evaluates to True, the program continues running normally. If it
evaluates to False, Python immediately halts execution and raises an
AssertionError
def calculate_discount(price, discount):
final_price = price - discount # Sanity check: Price can never be negative
assert final_price >= 0, "Discount cannot be higher than the actual price!"
return final_price
print(calculate_discount(100, 20)) # Output: 80
print(calculate_discount(50, 60)) # Raises AssertionError: Discount cannot be
higher than the actual price!
EXCEPTION HANDLING
Errors in python
[Link] errors
These are the syntactical errors in the code and are found during
compile time.
Example:forgetting a colon in statements like if,while,for,def etc
[Link] Errors
These are the errors in logic of [Link] are not detected
either by compiler or PVM.
Example:Using wrong formula for the application.
[Link] Errors
These errors are found during execution and are detected by
PVM.
Example:insufficient memory to store data.
EXCEPTION
1. Exception is a runtime error that can be handled by programmer.
2. All exceptions in python are represented as classes.
3. Exceptions which are already available in python are called built in
exceptions.
4. The base class for built in exceptions is ‘BaseException’.
5. ‘Exception’ sub class is derived from ‘BaseException’.
6. From ‘Exception’ class the sub class ‘StandardError’ and ‘Warning’
are derived.
7. All exceptions are defined as subclasses of ‘StandardError’.
8. All warnings are defined as subclasses of ‘Warning’.
Exception Handling
Exceptions should be handled to make the program robust(strong).
Exception handling is done using try-except-finally-else blocks.
Try block contains the statements where there is possibility for
exception.
Except block handles the exception that are raised in try block.
Finally block is always excuted irrespective of whether there is an
exception or not.
Syntax
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Program
a =[1, 2, 3]
try:
print("Second element = %d"%(a[1]))
# Throws error since there are only 3 elements in array
print("Fourth element = %d"%(a[3]))
exceptIndexError:
print("An error occurred")
Output:
Second element = 2
An error occurred
Program to open a file where you do not have write permission, so it
raises an exception
try:
f = open("testfile", "r")
[Link]("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
finally:
print('This is always executed')
Output:
Error: can't find file or read data
This is always executed
Multiple Exceptions
Multiple Except blocks are used to handle multiple exceptions.
try:
a=3
if a > 4:
b = a / (a - 3)
except NameError:
print("Name Error")
except ZeroDivisionError:
print("Division Error")
Output:
Error Occurred and Handled
The above program can also be written as
try:
a=3
if a < 4:
b = a / (a - 3)
# note that braces () are necessary for multiple exceptions
except(ZeroDivisionError, NameError):
print("Error Occurred and Handled")
Output:
Error Occurred and Handled.
Public Access Modifier
Members (variables or methods) declared as public can be
accessed from anywhere in the program.
By default, all members are public in Python.
class Geek:
def __init__(self, name, age):
[Link] = name
[Link] = age
def displayAge(self):
print("Age:", [Link])
obj = Geek("R2J", 20)
print("Name:", [Link])
[Link]()
Output
Name: R2J
Age: 20
Private Access Modifier
A member is private if its name starts with double underscores
(__).
class Geek:
def __init__(self, name, roll, branch):
self.__name = name
self.__roll = roll
self.__branch = branch
def __displayDetails(self):
print("Name:", self.__name)
print("Roll:", self.__roll)
print("Branch:", self.__branch)
def accessPrivateFunction(self):
self.__displayDetails()
obj = Geek("R2J", 1706256, "CSE")
[Link]()
print(obj._Geek__name)
Output
Name: R2J
Roll: 1706256
Branch: CSE
R2J
Explanation:
__name, __roll, __branch: private variables
__displayDetails(): private method
Direct access from outside will raise AttributeError
Access allowed inside the class or via name mangling
(obj._Geek__name)
Name Mangling
Although name-mangled variables are meant to be protected,
they can still be accessed using the mangled name.
class Student:
def __init__(self, name):
self.__name = name
s = Student("Jake")
print(s._Student__name)
Output
Jake
GUI programming with TKINTER
Tkinter is Python’s built-in library for creating graphical user interfaces (GUIs).
Graphical User Interface (GUI) applications are software programs that display an
interface on the screen with which users can interact . These interfaces typically
feature visual elements like buttons and [Link] applications are designed to make
it easier for users to complete tasks
Tk()
In Tkinter, the Tk() class is used to create the main application window. Every
Tkinter program starts by creating exactly one Tk() object.
root = [Link]()
root is object for tkinter class tk()
mainloop()
The mainloop() method starts the event loop of a Tkinter application. It keeps the
window open, waits for user actions (like mouse clicks or key presses), and
processes events until the window is closed.
syntax:
[Link]()
program
import tkinter as tk
root = [Link]()
# Widgets are added here
[Link]()
Output
[Link](): Creates the main application window.
[Link](): Starts the event loop and keeps the window responsive.
The program stops only when the window is closed.
Label
The Label widget is used to display text or images in a Tkinter window.
import tkinter as tk
root = [Link]()
label = [Link](root, text="This is python class")
[Link]()
[Link]()
[Link]() places the label inside the window.
Button
The Button widget is a clickable component used to perform an action when
pressed, such as submitting data or closing a window.
button = [Link](master, option=value)
import tkinter as tk
root = [Link]()
[Link]("Counting Seconds")
button = [Link](root, text="Stop", width=25, command=[Link])
[Link]()
[Link]()
Output
command=[Link]: Closes the application when the button is clicked.
[Link](): Places the button in the window.
3. Entry
The Entry widget is used to accept single-line text input from the user. For multi-
line text input, the Text widget is used instead.
import tkinter as tk
root = [Link]()
[Link](root, text="First Name").grid(row=0, column=0)
[Link](root, text="Last Name").grid(row=1, column=0)
entry1 = [Link](root)
entry2 = [Link](root)
[Link](row=0, column=1)
[Link](row=1, column=1)
[Link]()
Output
Listbox
The Listbox widget displays a list of items from which the user can select one or
more options.
import tkinter as tk
root = [Link]()
lb = [Link](root)
[Link](1, "Python")
[Link](2, "Java")
[Link](3, "C++")
[Link](4, "Any other")
[Link]()
[Link]()
Output
[Link](): Creates a list container.
insert(): Adds items to the listbox.
pack(): Displays the listbox in the window.
Menu
The Menu widget is used to create menu bars and dropdown menus in a Tkinter
application. Below is the syntax:
menu = [Link](master, option=value)
Example: This example creates a menu bar with File and Help menus.
import tkinter as tk
root = [Link]()
menu = [Link](root)
[Link](menu=menu)
filemenu = [Link](menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New")
filemenu.add_command(label="Open...")
filemenu.add_separator()
filemenu.add_command(label="Exit", command=[Link])
helpmenu = [Link](menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About")
[Link]()
Output
A window appears with a menu bar containing File and Help options.
Explanation:
[Link](): Creates a menu container.
add_cascade(): Adds dropdown menus to the menu bar.
add_command(): Adds menu items.
add_separator(): Adds a dividing line.
[Link](menu=menu): Attaches the menu bar to the window.
Event Handling in Tkinter
In Tkinter, events are actions that occur when a user interacts with the GUI, such as
pressing a key, clicking a mouse button or resizing a window. Event handling allows
us to define how our application should respond to these interactions.
import tkinter as tk
def on_key_press(event):
print(f"Key pressed: {[Link]}")
def on_left_click(event):
print(f"Left click at ({event.x}, {event.y})")
def on_right_click(event):
print(f"Right click at ({event.x}, {event.y})")
def on_mouse_motion(event):
print(f"Mouse moved to ({event.x}, {event.y})")
root = [Link]()
[Link]("Advanced Event Handling Example")
[Link]("<KeyPress>", on_key_press)
[Link]("<Button-1>", on_left_click)
[Link]("<Button-3>", on_right_click)
[Link]("<Motion>", on_mouse_motion)
[Link]()