Python OOP: Classes, Objects & More
Python OOP: Classes, Objects & More
MODULE-03
Object Oriented Programming: Classes and Objects; Creating Classes and Objects;
Constructor Method; Classes with Multiple Objects; Objects as Arguments; Objects as Return
Values; Inheritance- Single and Multiple Inheritance, Multilevel and Multipath Inherita nce ;
Encapsulation-Definition, Private Instance Variables; Polymorphism- Definition, Operator
Overloading.
GU Interface: The tkinter Module; Window and Widgets; Layout Management- pack, grid
and place.
Python SQLite: The SQLite3 module; SQLite Methods- connect, cursor,execute, close;
Connect to Database; Create Table; Operations on Tables-Insert, Select, Update. Delete and Drop
Records.
Data Analysis: NumPy- Introduction to NumPy, Array Creation using NumPy, Operations on
Arrays; Pandas- Introduction to Pandas, Series and DataFrames, Creating DataFrames from
Excel Sheet and .csv file,Dictionary and Tuples. Operations on DataFrames.
Data Visualisation: Introduction to Data Visualisation; Matplotlib Library; Differe nt
Types of Charts using Pyplot- Line chart, Bar chart and Histogram and Pie chart.
CLASS
In object-oriented programming (OOP), a class is a blueprint or template for
creating objects (instances).
It defines the common attributes (data) and behaviors (methods) that objects of
that class will have.
A class serves as a blueprint from which objects are created, each possessing its
own unique set of data.
In simple terms, a class is like a blueprint for creating objects, and an object is
aninstance of a class.
[Link] = year
def drive(self):
In this example, the Car class has three attributes: make, model, and year.
These attributes represent the data associated with a car object, such as its
make (e.g., Toyota), model (e.g., Camry), and year of manufacture.
The class also has two methods: drive() and stop().
These methods define the behavior or actions that a car object can perform.
For example, the drive() method prints a message indicating that the car is
driving, and the stop() method prints a message indicating that the car has
stopped.
OBJECT
In this example, my_car is an object of the Car class. It represents a specific car
instance with the make "Toyota", model "Camry", and year 2021.
Once an object is created, we can access its attributes and methods using dot notation.
For example:
In this code we access the attributes of my_car (make, model, year) using dot notation
(my_car.make, my_car.model, my_car.year). We can also call the methods of my_car
(drive(), stop()) using dot notation (my_car.drive(), my_car.stop()).
Each object of a class can have its own set of attribute values, which makes it distinct
and separate from other objects of the same class.
CREATING CLASS
To create a class in Python, you can use the class keyword followed by the name of the class.
The class can contain attributes (data) and methods (functions) that define its behavior. Here's
a basic example of creating a class in Python:
class MyClass:
def greet(self):
obj = MyClass("John")
In the above example, we define a class named MyClass. It has an init method
(constructor) that initializes the name attribute of the class. The greet method is a
simple method that prints a greeting message using the name attribute.
To create an instance (object) of the class, we simply call the class name followed by
parentheses, passing any required arguments to the init method. In this case, we
create an object obj of MyClass and pass the name "John" to initialize the name
attribute.
We can then access the attributes and call the methods of the object using the dot
notation. In the example, we print the value of the name attribute and call the greet
method to display the greeting message.
By creating classes in Python, you can define your own custom types with specific
attributes and behaviors, encapsulating related data and functionality into a single
unit.
CREATING OBJECT
To create an object in Python, you need to instantiate a class. An object, also referred
to as an instance, is a specific occurrence of a class, representing a unique entity with
its own set of attributes and behaviors. Here's an example of creating an object in
Python:
class MyClass:
[Link] = name
def greet(self):
obj = MyClass("John")
In the example above, we have a class called MyClass with an init method that
initializes the name attribute. To create an object, we use the class name followed by
parentheses and pass any required arguments to the init method. In this case, we create
an object named obj and pass the name "John" as an argument.
Once the object is created, you can access its attributes and call its methods using the
dot notation. For instance, you can access the name attribute of the object using
[Link]. Similarly, you can call the greet method of the object using [Link]().
Here's an example of accessing the attributes and calling methods of the created object:
In the code above, we print the value of the name attribute using [Link], and then
we call the greet method using [Link](), which will display the greeting message
"Hello, John!".
By creating objects in Python, you can work with instances of classes and utilize
their attributes and behaviors to perform specific tasks and operations.
[Link] = width
[Link] = height
def area(self):
rectangle1 = Rectangle(4, 5)
rectangle2 = Rectangle(3, 6)
print([Link]) # Output: 4
print([Link]) # Output: 5
print([Link]()) # Output: 20
print([Link]) # Output: 3
print([Link]) # Output: 6
print([Link]()) # Output: 18
In this example, we define the Rectangle class with an init method that initializes
the width and height attributes of each object.
The class also has a method called area that calculates and returns the area of the
rectangle.
We then create two objects, rectangle1 and rectangle2, by calling the Rectangle class
constructor with different arguments.
Each object has its own set of width and height attributes.
We can access the attributes (width, height) and call the method (area) of each object
separately.
The attributes and methods of each object are independent of each other.
By creating multiple objects of a class, you can represent multiple instances of the
same entity or concept, each with its own unique set of data and behavior.
This allows you to work with and manipulate distinct objects individually, enabling
modular and reusable code structures.
OBJECTS AS ARGUMENTS
class Rectangle:
def init (self, width, height):
[Link] = width
[Link] = height
def area(self):
return [Link] * [Link]
def print_rectangle_area(rect):
area = [Link]()
ROOPA 2023-24 JSSCACS
7
PYTHON PROGRAMMING QPCODE:14408
Example
class Rectangle:
[Link] = width
[Link] = height
def area(self):
def create_square(side_length):
return square
my_square = create_square(5)
print(my_square.width) # Output: 5
print(my_square.height) # Output: 5
print(my_square.area()) # Output: 25
In this example, we have a Rectangle class with an init method to initialize the
width and height attributes and an area method to calculate the area of the rectangle.
The create_square function takes a side_length parameter and creates a square object
by creating an instance of the Rectangle class with equal width and height. The square
object is then returned as the output of the function.
We call the create_square function with a side length of 5 and store the returned object
in the variable my_square. We can then access the attributes (width, height) and call
the method (area) of the my_square object.
By returning objects from functions, you can perform operations on objects and
encapsulate the resulting object within the function. This allows you to create and
manipulate objects in a more modular and flexible way, enabling code reuse and
promoting a clean and organized code structure.
INHERITANCE
Inheritance can be defined as a process through which one class acquires the
features(attributes and methods) of an existing class without modifying it.
The class which inherits the features is referred to as child class or derived class and
the class from which the features inherited is referred to as parent class or base class.
In other words, the newly formed class is the child class while the existing class is
known as the parent class.
For instance, in the real world, a father and mother denote the parent class while their
kids denote the child class.
A kid has acquired several features from their parents and at the same time, the kid
has got some unique features that the parents may not have. In programming terms,
we can say that a child class acquires all the attributes and methods of a parent class,
but at the same time child class holds its own unique characteristics.
Syntax
Class Parent_class:
Body of parent_class
Class Child_class(Parent_class):
Body of Child_class
o Single Inheritance
o Multilevel Inheritance
o Hierarchical Inheritance
o Multiple Inheritance
o Hybrid Inheritance
Syntax
class ParentClass:
class ChildClass(ParentClass):
Example
Multilevel inheritance is a type of inheritance where a class is created from a derived class
which itself inherits a base class. A multilevel inheritance shows the possibility of inheriting
from a derived class or child class. So a minimal multilevel inheritance is 3 tier structure with
a child class that inherits features from a derived class which in turn inherits the properties
from a superclass
Syntax
class Grandparent:
# Grandparent class attributes and methods
class Parent(Grandparent):
# Parent class attributes and methods
class Child(Parent):
# Child class attributes and methods
In this example, the DerivedClass inherits from the IntermediateClass, which in turn inherits
from the BaseClass, creating a multilevel inheritance chain. The DerivedClass can access and
extend the attributes and methods defined in both parent classes.
Example
[Link] = name
[Link] = age
[Link] = salary
[Link] = name
[Link] = age
[Link] = salary
[Link] = name
[Link] = age
[Link] = salary
emp1 = employee('harshit',22,1000)
emp2 = childemployee1('arjun',23,2000)
print([Link])
print([Link])
Output: 22,23
Multiple Python Inheritance
Syntax
class ParentClass1:
class ParentClass2:
# Parent Class 2 attributes and methods
class ChildClass(ParentClass1, ParentClass2):
# Child Class attributes and methods
ROOPA 2023-24 JSSCACS
12
PYTHON PROGRAMMING QPCODE:14408
In this the Child Class inherits from both ParentClass1 and ParentClass2 using
multiple inheritance.
The child class can access and extend the attributes and methods defined in both
parent classes.
However, it's important to carefully handle potential conflicts or ambiguity that may
arise from inheriting multiple classes with overlapping names or functionalities.
Example
class employee1(): //Parent class
def init (self, name, age, salary):
[Link] = name
[Link] = age
[Link] = salary
class employee2(): //Parent class
def init (self,name,age,salary,id):
[Link] = name
[Link] = age
[Link] = salary
[Link] = id
class childemployee(employee1,employee2):
def init (self, name, age, salary,id):
[Link] = name
[Link] = age
[Link] = salary
[Link] = id
emp1 = employee1('harshit',22,1000)
emp2 = employee2('arjun',23,2000,1234)
Hierarchical Inheritance
The derived classes can access and extend the functionality defined in the Base Class.
They can add their own unique attributes and methods while still inheriting and
utilizing the common features defined in the base class.
Syntax:
class BaseClass:
# Base class attributes and methods
class DerivedClass1(BaseClass):
# Derived class 1 attributes and methods
class DerivedClass2(BaseClass):
# Derived class 2 attributes and methods
In this both DerivedClass1 and DerivedClass2 inherit from the BaseClass,
demonstrating hierarchical inheritance. The derived classes can access and extend the
attributes and methods defined in the base class.
Example
class employee():
[Link] = name
[Link] = age
[Link] = salary
class childemployee1(employee):
[Link] = name
[Link] = age
[Link] = salary
class childemployee2(employee):
[Link] = name
[Link] = age
[Link] = salary
emp1 = employee('harshit',22,1000)
emp2 = employee('arjun',23,2000)
ROOPA 2023-24 JSSCACS
14
PYTHON PROGRAMMING QPCODE:14408
Syntax
class BaseClass1:
In a typical inheritance hierarchy, a derived class can inherit from a single base class.
However, in multipath inheritance, a derived class can inherit from multiple base
classes, which can lead to more complex relationships and potential conflicts.
Example
class A:
def method_a(self):
print("This is method A.")
class B(A):
def method_b(self):
print("This is method B.")
class C(A):
def method_c(self):
print("This is method C.")
class D(B, C):
def method_d(self):
print("This is method D.")
In this example, class D inherits from both class B and class C, which means it
indirectly inherits from class A through multiple paths. Here's how the inheritance
hierarchy looks:
A
/ \
B C
\ /
D
As a result, class D has access to all the methods and attributes of classes A, B, and C.
However, if there are conflicts between methods or attributes inherited from multiple
paths (e.g., if both class B and class C have a method with the same name), it can
create ambiguity, and the programmer needs to carefully handle such cases.
Multipath inheritance can offer flexibility and code reuse in certain scenarios, but it
can also make the code more complex and harder to maintain. Therefore, it is
generally recommended to use multipath inheritance judiciously and consider
Modular Codebase: Increases modularity, i.e., breaking down the codebase into
modules, making it easier to understand. Here, each class we define becomes a
separate module that can be inherited separately by one or many classes.
Code Reusability: the child class copies all the attributes and methods of the parent class
into its class and use. It saves time and coding effort by not rewriting them, thus following
modularity paradigms.
Less Development and Maintenance Costs: changes must be made in the base class,
and all derived classes will automatically follow.
Reusability – Inheritance allows obtaining new classes from existing classes without
modification. This helps reusability of information in the child class and adds extra
functionality.
Decreases the Execution Speed: loading multiple classes because they are
interdependent
Tightly Coupled Classes: Even though parent classes can be executed
independently, child classes can only be conducted by defining their parent classes.
CONSTRUCTOR
In Python, the method the init () simulates the constructor of the class. This
method is called when the class is [Link] accepts the self-keyword as a first
argument which allows accessing the attributes or method of the class.
We can pass any number of arguments at the time of creating the class object,
depending upon the init () definition. It is used to initialize the class attributes.
The constructor method must be named init . This is a special name that is
recognized by Python as the constructor method.
The first argument of the constructor method must be self. This is a reference to
the object itself, and it is used to access the object’s attributes and methods.
The constructor method must be defined inside the class definition. It cannot
bedefined outside the class.
The constructor method is called automatically when an object is created. You don’t
need to call it explicitly.
You can define both default and parameterized constructors in a class. If you define
both, the parameterized constructor will be used when you pass arguments to the
object constructor, and the default constructor will be used when you don’t pass any
arguments.
Example
class Employee:
def init (self, name, id):
[Link] = id
[Link] = name
def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))
emp1 = Employee("Janav", 101)
emp2 = Employee("Divya", 102)
[Link]() # accessing display() method to print employee 1 information
[Link]() # accessing display() method to print employee 2 information
Output:
ID: 101
Name: Janav
ID: 102
Name: Divya
Parameterized constructors are useful when you want to create an object with custom values
for its attributes. They allow you to specify the values of the object’s attributes when the object
is created, rather than using default values.
Here is an example of a class with a parameterized constructor:
class Person:
def init (self, name, age):
[Link] = name
[Link] = age
person = Person("Alice", 25)
print([Link])
print([Link])
Output:
Alice
25
In this example, the init method is the parameterized constructor for
the Person class.
It takes two arguments, name and age, and it sets the values of
the name and age attributes of the object to the values of these arguments.
Default constructors are useful when you want to create an object with a predefined set of
attributes, but you don’t want to specify the values of those attributes when the object is created.
Here is an example of a default constructor:
Example
class Person:
[Link] = "John"
[Link] = 30
person = Person()
print([Link])
print([Link])
Output:
John
30
In this example, the init method is the default constructor for the Person class. It is called
automatically when the object is created, and it sets the default values for the name and age
attributes.
NON-PARAMETERIZED CONSTRUCTORS
Example
class MyClass:
def init (self):
self.arg1 = 10
self.arg2 = 20
obj = MyClass()
print(obj.arg1)
print(obj.arg2)
Output:
10
20
In this case, the non-parameterized constructor is used to initialize the default values for the
instance variables arg1 and arg2. If you create an instance of the MyClass class without
passing any arguments, the default values will be used.
ENCAPSULATION
They are typically denoted by prefixing an underscore (_) to their names. Although
Python doesn't enforce strict data hiding or access restrictions, the use of the underscore
convention indicates that the variable should be treated as private and should not be accessed
directly from outside the class.
Example
class Person:
self._name = name
self._age = age
def get_name(self):
return self._name
def get_age(self):
return self._age
if age > 0:
self._age = age
print(person.get_age()) # Output: 25
print(person._age) # Output: 25
person.set_age(30)
print(person.get_age()) # Output: 30
In this example, the Person class has private instance variables _name and _age.
These variables are accessed through public methods get_name() and get_age().
The set_age() method is provided to modify the _age variable, but with validation to
ensure a positive age value.
POLYMORPHISM
Polymorphism is having different forms. Polymorphism refers to a function having the same
name but being used in different ways and different [Link] basically creates a structure that
can use many forms of objects. This polymorphism may be accomplished in two distinct ways:
overloading and overriding.
Operator overloading
Operator overloading is a kind of overloading in which an operator may be used in ways other
than those stated in its predefined definition.
>>>print(2*7)
14
>>>print("a"*3)
aaa
Thus, in the first example, the multiplication operator multiplied two numbers; but, in the
second, since
multiplication of a string and an integer is not feasible, the character is displayed three times
twice.
Example
class example:
self.X = X
object_1 = example( int( input( print ("Please enter the value: "))))
object_2 = example( int( input( print ("Please enter the value: "))))
Output
: 44
: PythonProgramming
Python with Tkinter provides us a faster and efficient way in order to build
useful applications that would have taken much time if you had toprogram
directly in C/C++ with the help of native OS system libraries.
INSTALL TKINTER
Tkinter may be already installed on your system along with Python. But it is not
true always. So let's first check if it is available.
If you do not have Python installed on your system - Install Python
3.8 first, and then check for Tkinter.
You can determine whether Tkinter is available for your Python interpreter by
attempting to import the Tkinter module - If Tkinter is available, then there
will be no errors, as demonstrated in the following code:
import tkinter
If you see any error like module not found, etc, then your Python interpreter was
not compiled with Tkinter enabled, the module import fails and you might need to
recompile your Python interpreter to gain access to Tkinter.
The top-level window object in GUI Programming contains all of the little
window objects that will be part of your complete GUI.
The little window objects can be text labels, buttons, list boxes, etc., and these
individual little GUI components are known as Widgets.
If you see any error like module not found, etc, then your Python interpreter was not
compiled with Tkinter enabled, the module import fails and you might need to
recompile your Python interpreter to gain access to Tkinter.
2. The second step is to create a top-level windowing object that contains your
entire GUI application.
3. Then in the third step, you need to set up all your GUI components and their
functionality.
4. Then you need to connect these GUI components to the underlying
application code.
5. Then just enter the main event loop using mainloop()
TKINTER WINDOWS
The top-level window object in GUI Programming contains all of the little
window objects that will be part of your complete GUI.
The little window objects can be text labels, buttons, list boxes, etc., and these
individual little GUI components are known as Widgets
So, having a top-level window object will act as a container where you will put all
your widgets. In Python, you'd typically do so like this using the following code: win
= [Link]()
The object that is returned by making a call to [Link]() is usually referred to
as the Root Window.
Top-level windows are mainly stand-alone as part of your application, also you can
have more than one top-level window for your GUI
First of all, you need to design all your widgets completely, and then addthe real
functionality.
The widgets can either be stand-alone or can be containers. If one widget contains
other widgets, it is considered the parent of those widgets.
Similarly, if a widget is contained within another widget, it's known as achild of the
parent, the parent is the next immediate enclosing container widget.
The widgets also have some associated behaviours, such as when a button is pressed,
or text is filled into a text field, so we have a Tkinter Windows The term "Window"
has different meanings in the different contexts, But generally "Window" refers to a
rectangular area somewhere on the user's display screen through which you can
interact.
As mentioned earlier that in GUI programming all main widgets are only built on the top-
level window object.
This method is mainly used to create the main window. You can also change the name of
the window if you want, just by changing the className to the desired one.
The code used to create the main window of the application and we have also used it in our
above example:
win = [Link]() ## where win indicates name of the main window object
The pack() method mainly uses a packing algorithm in order to place widgets in
a Frame or window in a specified order.
This method is mainly used to organize the widgets in a block.
Packing Algorithm:
[Link](options)
1. Fill:The default value of this option is set to NONE. Also, we can set it to X or Y in
order to determine whether the widget contains any extra space.
2. Side
This option specifies which side to pack the widget against. If you want to pack
widgets vertically, use TOP which is the default value. If you want to pack widgets
horizontally, use LEFT.
3. Expand
This option is used to specify whether the widgets should be expanded to fill any
extra space in the geometry master or not. Its default value
is false. If it is false then the widget is not expanded otherwise widget expands to
fill extra space.
import tkinter as tk
win = [Link]()
# add an orange frame
frame1 = [Link](master=win, width=100, height=100, bg="orange")
[Link]()
# add blue frame
frame2 = [Link](master=win, width=50, height=50, bg="blue")
[Link]()
# add green frame
frame3 = [Link](master=win, width=25, height=25, bg="green")
[Link]()
[Link]()
According to the output of the above code, the pack() method just places
each Frame below the previous one by default, in the same order in which they're
assigned to the window.
Let's take a few more code examples using the parameters of this function like fill, side
and, expand.
You can set the fill argument in order to specify in which direction you want the
frames should fill.
If you want to fill in the horizontal direction then the option is tk.X, whereas,
tk.Y is used to fill vertically, and to fill in both
directions [Link] is used.
The most used geometry manager is grid() because it provides all the power of pack()
function but in an easier and maintainable way.
The grid() geometry manager is mainly used to split either a window or frame into rows and
columns.
Index of both the row and column starts from 0, so a row index of 2 and acolumn
index of 2 tells the grid() function to place a widget in the third column of the third
row(0 is first, 1 is second and 2 means third).
[Link](options)
Column
This option specifies the column number in which the widget is to beplaced. The
index of leftmost column is 0.
Row
This option specifies the row number in which the widget is to be placed. The topmost
row is represented by 0.
Columnspan
This option specifies the width of the widget. It mainly represents the number of
columns up to which, the column is expanded.
Rowspan
This option specifies the height of the widget. It mainly represents the number of
rows up to which, the row is expanded.
padx, pady
ipadx, ipady
This option is mainly used to represents the number of pixels of padding to be added
to the widget inside the widget's border
This method basically organizes the widget in accordance with its x and ycoordinates.
Both x and y coordinates are in pixels.
Thus the origin (where x and y are both 0) is the top-left corner ofthe Frame
or the window.
Thus, the y argument specifies the number of pixels of space from the top of the
window, to place the widget, and the x argument specifies
the number of pixels from the left of the window.
[Link](options)
x, y
This option indicates the horizontal and vertical offset in the pixels.
height, width
This option indicates the height and weight of the widget in the pixels.
Anchor
This option mainly represents the exact position of the widget within the container.
The default value (direction) is NW that is (the upper left corner).
bordermode
This option indicates the default value of the border type which
is INSIDE and it also refers to ignore the parent's inside the border. The other option
is OUTSIDE.
relx, rely
This option is used to represent the float between 0.0 and 1.0 and it is the offset in
the horizontal and vertical direction.
relheight, relwidth
This option is used to represent the float value between 0.0 and 1.0 indicating
the fraction of the parent's height and width.
PYTHON WIDGETS
To display a single-line text field that accepts values from the user
Entry
Entry widget will be used.
Listbox To provide a user with a list of options the Listbox widget will be used.
Menubutton The Menubutton widget is used to display the menu items to the user.
The message widget mainly displays a message box to the user. Basically it is
Message
a multi-line text which is non-editable.
To scroll the window up and down the scrollbar widget in python will be
Scrollbar
used.
The text widget mainly provides a multi-line text field to the user where
Text
users and enter or edit the text and it is different from Entry.
The SpinBox acts as an entry to the "Entry widget" in which value can
SpinBox
be input just by selecting a fixed value of numbers.
The LabelFrame widget is also a container widget used to mainly handle the
LabelFrame
complex widgets.
Label Widget
The label widget is mainly used to provide a message about the other widgets
used in the Python Application to the user.
You can change or update the text inside the label widget anytime you want.
This widget uses only one font at the time of displaying some text.
You can perform other tasks like underline some part of the text and you can also
span text to multiple lines.
There are various options available to configure the text or the part of the text shown
in the Label.
The syntax of the label widget is given below, W =
Label(master,options)
In the above syntax, the master parameter denotes the parent window. You can
use many options to configure the text and these options are written as comma- separated
key-value pairs.
Bd-This option is used for the border width of the widget. Its default value is 2
pixels.
Bg-This option is used for the background color of the widget.
Cursor-This option is used to specify what type of cursor to show when the mouse is
moved over the label. The default of this option is to use the standard cursor.
Fg-This option is used to specify the foreground color of the text that is written
inside the widget.
Font- This option specifies the font type of text inside the label.
Height-This option indicates the height of the widget
Button Widget
The Button widget in Tkinter is mainly used to add a button in any GUI
Application.
In Python, while using the Tkinter button widget, we can easily modify the style of
the button like adding a background colors to it, adjusting height and width of
button, or the placement of the button, etc. very easily.
Check-button widget.
It allows you to select multiple options or a single option at a time just by clicking
the button corresponding to each option.
For example, in a form, you see option to fill in your Gender, it has options,
Male, Female, Others, etc., and you can tick on any of the
options, that is a checkbox. We use the <input> tag in HTML, to create checkbox
It can either contain text or image. There are a number of options available to
configure the Checkbutton widget as per your requirement.
w=checkbutton(master,option=value)
In the above syntax, the master parameter denotes the parent window. You canuse many
options to configure your checkbutton widget and these options are written as comma-
separated key-value pair.
Radiobutton Widget
Tkinter radiobutton widget is used to implement multiple-choice options that are mainly
created in user input forms.
Allows the user to select only one option from the given ones. Thus it is also known
as implementing one-of-many selection in a Python Application.
Also, different methods can also be associated with radiobutton.
You can also display multiple line text and images on the radiobutton. Each
radiobutton displays a single value for a particular variable.
You can also keep a track of the user's selection of the radiobutton because
it is associated with a single variable
W = Radiobutton(master, options)
In the above syntax, the master parameter denotes the parent window. You can use many
options to change the look of the radiobutton and these options are written as comma-
separated key-value pairs.
Menu Widget
The following types of menus can be created using the Tkinter Menu widget:
pop-up, pull-down, and top level.
Top-level menus are those menus that are displayed just under the title bar of the
root or any other top-level windows. For example, all the websites have a top
navigation menu just below the URL bar in the browser.
Menus are commonly used to provide convenient access to options like opening
any file, quitting any task, and manipulating data in anapplication.
W = Menu(master, options)
In the above syntax, the master parameter denotes the parent window. You can use many
options to change the look of the menu and these options are written as comma-separated key-
value pairs.
Cursor-This option will convert the mouse pointer to the specified cursor type and it
can be set to an arrow, dot, etc.
Font-This option is used to represent the font type of the text of the widget.
Fg-This option is used to represent the foreground color of the text of the widget.
Height-This option indicates the vertical dimension of the widget
Width-This option indicates the horizontal dimension of the widget and it is
represented as the number of characters.
Padx-This option represents the horizontal padding of the widget.
Pady-This option represents the vertical padding of the widget
Frame Widget
The Tkinter Frame widget is used to group and organize the widgets in a better and friend ly
way.
The Frame widget is basically a container (an invisible container) whose task is to hold other
widgets and arrange them with respect to each other.
syntax
W = Frame(master, options)
In the above syntax, the master parameter denotes the parent window. You can use many
options to change the look of the frame and these options are written as comma-separated
key-value pairs.
bd-This option is used to represent the width of the border. Its default value is 2
pixels.
Canvas Widget
Tkinter Canvas widget is mainly used as a general-purpose widget which is used to
draw anything on the application window in Tkinter.
This widget is mainly used to draw graphics and plots, drawings, charts, and
showing images
You can draw several complex layouts with the help of canvas, for example,
polygon, rectangle, oval, text, arc bitmap, graphics, etc.
Canvas widget is also used to create graphical editors.
Syntax
w = Canvas(master, option=value)
In the above syntax, the master parameter denotes the parent window. You can use many
options to change the layout of the canvas and these options are written as comma-separated
key-values.
You can use various styles and attributes with the Text widget.
You can also use marks and tabs in the Text widget to locate the specific sections of
the text.
Media files like images and links can also be inserted in the Text Widget. There
are some variety of applications where you need multiline text like sending messages or
taking long inputs from users, or to show editable
long format text content in application, etc. use cases are fulfilled by this widget.
Thus in order to show textual information, we will use the Text widget.
syntax
W = Text(master, options)
In the above syntax, the master parameter denotes the parent window.
You can use many options to configure the text editor and these options are written
as comma-separated key-value pairs.
Listbox Widget
The items contain the same type of font and the same font color.
It is important to note here that only text items can be placed inside a Listbox
widget.
From this list of items, the user can select one or more items according tothe
requirements.
Syntax
W = Listbox(master, options)
In the above syntax, the master parameter denotes the parent window. You can use
many options to change the look of the ListBox and these options are written as
comma-separated key-value pairs.
PYTHON SQLITE
SQLITE FEATURES
Following is a list of features which makes SQLite popular among other lightweight
databases:
SQLite is totally free: SQLite is open-source. So, no license is required to work with
it.
SQLite is serverless: SQLite doesn't require a different server process or system to
operate.
SQLite is very flexible: It facilitates you to work on multiple databases on the
same session at the same time.
ROOPA 2023-24 JSSCACS
49
PYTHON PROGRAMMING QPCODE:14408
It allows you to perform various database operations, such as creating tables, inserting
data, querying data, updating data, and deleting data.
Here's an overview of the SQLite3 module and its functionality:
SQLITE METHODS
dbName = '[Link]'
try:
conn = [Link](dbName)
cursor = [Link]()
print("Database created!")
except Exception as e:
if conn:
[Link]()
If we look at the folder where our Python script is, we should see a new file called
[Link]. This file has been created automatically by sqlite3
Close cursor and connection objects
use [Link]() and [Link]() method to close the cursor and SQLite
connections after your work completes
import sqlite3
try:
sqliteConnection = [Link]('SQLite_Python.db')
cursor = [Link]()
[Link](sqlite_select_Query)
record = [Link]()
[Link]()
finally:
if sqliteConnection:
[Link]()
OPERATIONS ON TABLE
Create Table
To create a table in SQLite, you use the CREATE TABLE statement.
Syntax
column1 datatype,
column2 datatype,
...
);
Example:
name TEXT,
age INTEGER,
city TEXT
);
Insert
To insert data into a table, you use the INSERT INTO statement.
Syntax
Example:
Update
To update existing data in a table, you use the UPDATE statement.
Syntax
UPDATE table_name
WHERE condition;
UPDATE employees
SET age = 30
WHERE id = 1;
Delete
To delete data from a table, you use the DELETE FROM statement.
Syntax
WHERE condition;
WHERE id = 1;
Querying data
To retrieve data from a table, you use the SELECT statement.
Syntax
FROM table_name
WHERE condition;
Filtering data
You can use the WHERE clause to filter data based on specific conditions.
Syntax
FROM table_name
WHERE condition;
Sorting data
You can use the ORDER BY clause to sort the data in a specific order.
Syntax
FROM table_name
NUMPY
NumPy is a powerful Python library for numerical computing that provides support for
efficient operations on large, multi-dimensional arrays and matrices.
The name "NumPy" is short for "Numerical Python." It is widely used in scientific
computing, data analysis, and machine learning due to its performance, versatility, and
extensive set of mathematical functions.
Arrays:
The fundamental data structure in NumPy is the nd array, which stands for N-
dimensional array.
It is a homogeneous collection of elements with a fixed size in memory.
Arrays can have one or more dimensions and can store data of different types, such as
integers, floating-point numbers, or even complex numbers.
Vectorized operations:
Array creation:
NumPy provides powerful indexing and slicing capabilities to access and manipulate
elements within arrays.
You can use integers, slices, to extract specific elements or subsets of arrays based on
conditions.
Broadcasting:
Mathematical functions:
NumPy provides several functions for creating arrays with different properties and initial
values.
print(arr1)
Output: [1 2 3 4 5]
print(arr2)
Output:
[[1 2 3]
[4 5 6]]
print(arr3)
Output:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
print(arr4)
Output:
[[1. 1. 1.]
[1. 1. 1.]]
print(arr5)
Output:
[0 2 4 6 8]
print(arr6)
Output:
print(arr7)
Output:
[[0.56935657 0.69338216]
[0.12691842 0.50071383]
ROOPA 2023-24 JSSCACS
59
PYTHON PROGRAMMING QPCODE:14408
[0.14643409 0.9199429 ]]
arr8 = [Link](1, 10, (2, 3)) # low, high, shape as arguments for random
integers between 1 and 10
print(arr8)
Output:
[[7 2 1]
[9 8 5]]
NumPy provides a wide range of operations for manipulating arrays efficiently. Here are
some common operations you can perform on arrays using NumPy:
print(arr_sum)
Output: [ 6 8 10 12]
print(arr_diff)
Output: [4 4 4 4]
print(arr_prod)
Output: [ 5 12 21 32]
print(arr_div)
v)arr_pow = arr1 ** 2
print(arr_pow)
Output: [ 1 4 9 16]
i)arr_sum = [Link](arr)
print(arr_sum)
Output: 15
ii)arr_mean = [Link](arr)
print(arr_mean)
Output: 3.0
iii)arr_median = [Link](arr)
print(arr_median)
Output: 3.0
iv)arr_std = [Link](arr)
print(arr_std)
Output: 1.4142135623730951
v)arr_min = [Link](arr)
print(arr_min)
Output: 1
vi)arr_max = [Link](arr)
print(arr_max)
Output: 5
print(arr_reshaped)
Output:
[[1 2]
[3 4]
[5 6]]
ii)arr_transposed = [Link](arr)
print(arr_transposed)
Output:
[[1 4]
[2 5]
[3 6]]
print(arr_concatenated)
Output:
[[1 2 3]
[4 5 6]
[1 2 3]
[4 5 6]]
i)arr_exp = [Link](arr)
print(arr_exp)
ii)arr_sqrt = [Link](arr)
print(arr_sqrt)
iii)arr_sin = [Link](arr)
print(arr_sin)
INTRODUCTION TO PANDAS
Pandas is a powerful and popular open-source Python library widely used for data
manipulation and analysis.
It provides easy-to-use data structures and data analysis tools, making it a go-to
library for working with structured and tabular data.
Pandas is built on top of NumPy, extending its capabilities with additional
functionality specifically designed for data manipulation tasks.
Data structures: Pandas introduces two primary data structures, namely Series and
DataFrame.
i. Series: A Series is a one-dimensional labelled array that can hold any data type. It
is similar to a column in a spread sheet or a single column of data in a NumPy
array, with associated index labels for each element.
ii. DataFrame: A DataFrame is a two-dimensional labelled data structure,
resembling a table or a spread sheet with rows and columns. It is composed of
multiple Series objects that share a common index, allowing efficient data
alignment. DataFrames provide a convenient way to store, manipulate, and
analyze tabular data.
iii. Data manipulation: Pandas provides a rich set of functions for data manipulation
tasks, such as filtering, sorting, merging, grouping, reshaping, and aggregating
data.
iv. Selection and filtering: You can select subsets of data from a DataFrame using
various indexing techniques, such as label-based indexing, integer-based indexing,
or Boolean indexing based on specific conditions.
v. Data cleaning and preprocessing: Pandas offers methods to handle missing data,
perform data imputation, remove duplicates, perform string operations, and
convert data types. These features are crucial for data cleaning and preprocessing
tasks.
vi. Merging and joining: Pandas allows you to merge or join multiple DataFrames
based on common columns or indices, enabling the combination of different
datasets into a single dataset.
vii. Grouping and aggregating: Pandas provides powerful tools for grouping data
based on one or more columns, and then performing aggregations or calculations
on these groups. This functionality is useful for performing data summarization
and generating insights from grouped data.
viii. Data input and output: Pandas supports reading and writing data in various file
formats, including CSV, Excel, SQL databases, and more. It simplifies the process
of loading data into a DataFrame and saving the modified data back to different
file formats.
ix. Integration with other libraries: Pandas integrates well with other libraries in
the Python data science ecosystem, such as NumPy, Matplotlib, and scikit-learn.
SERIES IN PANDAS
import pandas as pd
s = [Link](data, index)
Here, data can be a list, NumPy array, dictionary, or scalar value that represents the
data you want to store in the Series.
index is an optional parameter that specifies the labels for each element in the Series.
If not provided, a default integer index starting from 0 is assigned.
Example:- creating a Series:
import pandas as pd
s = [Link](data)
print(s)
Output:
0 10
1 20
2 30
3 40
4 50
In this example, a Series is created with the provided data list, and the default integer index is
assigned. The resulting Series is displayed, showing the elements along with their
corresponding index.
Indexing and slicing: You can access elements of a Series using the associated index
labels. Slicing can also be performed to select subsets of the Series.
Arithmetic operations: Series support element-wise arithmetic operations, such as
addition, subtraction, multiplication, and division, as well as mathematical functions
from NumPy.
Alignment: Series objects align data based on their index labels, allowing for
effortless operations between Series with different lengths or indexes. Missing values
are introduced as NaN (Not a Number) during alignment.
Handling missing data: Pandas provides methods to handle missing data in Series,
such as isnull(), notnull(), and fillna().
Data alignment and automatic labeling: When performing operations involving
multiple Series or combining Series into a DataFrame, Pandas aligns the data based
on index labels. It automatically labels the resulting data to ensure proper alignment.
Name attribute: Series can have a name attribute, which helps identify the Series
when it becomes part of a DataFrame or during data analysis.
DATAFRAME
To create a DataFrame in Pandas, you can use various methods. One common way is
by passing a dictionary of lists, arrays, or Series as input, where the keys of the
dictionary represent column names, and the values represent the data in each column.
Example:
import pandas as pd
data = {
df = [Link](data)
print(df)
Output:
1 Jane 30 London
2 Mike 28 Paris
3 Lisa 35 Tokyo
In this example, a DataFrame is created from the dictionary data, where each key
represents a column name and the corresponding value represents the data in that
column. The resulting DataFrame is displayed, showing the columns and their
respective data.
Indexing and selection: You can access specific rows, columns, or subsets of data using
various indexing techniques, such as label-based indexing, integer-based indexing, or
Boolean indexing.
Column and row operations: DataFrames support operations on columns, such as adding
new columns, modifying existing columns, or dropping columns. Rows can be added,
deleted, or modified using various methods.
Data alignment: Similar to Series, DataFrames align data based on their index labels when
performing operations involving multiple DataFrames or combining DataFrames with
different shapes.
Handling missing data: Pandas provides methods to handle missing data in DataFrames,
such as isnull(), notnull(), dropna(), and fillna().
Data aggregation and groupby: DataFrames support various operations for aggregating
data, including grouping data based on specific columns, performing calculations within
groups, and applying functions across groups.
Data input and output: Pandas offers functions to read and write data in different formats,
such as CSV, Excel, SQL databases, and more. It simplifies the process of loading data into a
DataFrame and saving modified data back to different file formats.
Pandas provides convenient functions to read data from Excel files and create
DataFrames. Here's an example of how to create a DataFrame from an Excel sheet
using Pandas:
import pandas as pd
df = pd.read_excel('[Link]', sheet_name='Sheet1')
print(df)
In this example, the read_excel() function is used to read the data from the Excel file
named [Link].
You need to specify the sheet name using the sheet_name parameter (e.g., 'Sheet1') to
read data from a specific sheet.
If the Excel file contains multiple sheets, you can also read all the sheets by omitting
the sheet_name parameter or passing None.
The resulting data from the Excel sheet is stored in the DataFrame df.
You can then perform various operations on the DataFrame, such as indexing,
filtering, and data manipulation.
If the Excel file contains multiple sheets and you want to read all the sheets into
separate DataFrames, you can use the read_excel() function with sheet_name=None.
It will return a dictionary of DataFrames, where each key represents the sheet name
and the corresponding value is the DataFrame containing the sheet data.
import pandas as pd
df_sheet1 = dfs['Sheet1']
df_sheet2 = dfs['Sheet2']
print(df_sheet1)
print(df_sheet2)
In this case, the read_excel() function reads all the sheets from the Excel file, and the
resulting dictionary of DataFrames is stored in the variable dfs.
You can access individual DataFrames by providing the sheet name as the key to the
dictionary.
By utilizing the read_excel() function, you can easily read data from Excel files and
create corresponding DataFrames, allowing you to perform various data analysis and
manipulation tasks using Pandas.
Example:
import pandas as pd
df = pd.read_csv('[Link]')
print(df)
In this example, the read_csv() function reads the data from the CSV file named
[Link].
The resulting data is stored in the DataFrame df. By default, the read_csv() function
assumes that the CSV file has a header row, which contains column names.
If the CSV file doesn't have a header row, you can specify header=None as an
argument to the function.
You can also customize various parameters of the read_csv() function to handle
specific CSV file formats or requirements.
Some common parameters include:
sep: Specifies the delimiter used in the CSV file. By default, it is a comma (,). You can
change it to a different character or string if your CSV file uses a different delimiter.
header: Specifies the row number(s) to use as column names. By default, it is 0 (the first
row). If the CSV file doesn't have a header row, you can set header=None and provide your
own column names later.
index_col: Specifies the column(s) to use as the index of the DataFrame. It can take either a
column name or column index.
usecols: Specifies the columns to read from the CSV file. You can provide a list of column
names or column indices to select specific columns.
dtype: Specifies the data type for specific columns. It can be a dictionary where the keys are
column names, and the values are the desired data types.
parse_dates: Specifies the columns to parse as dates. It can be a list of column names or
column indices.
import pandas as pd
print(df)
In this example, the CSV file is read with a semicolon (;) as the delimiter, and the first
row is used as the header row. The column named 'ID' is set as the index column.
Only the columns 'ID', 'Name', and 'Age' are read from the CSV file. The 'Age'
column is specified to have an integer data type, and the 'Birthdate' column is parsed
as dates.
By adjusting the parameters of the read_csv() function, you can handle various CSV
file formats, specify column names and types, and customize the DataFrame creation
according to your specific requirements.
0 Janav 25 Mysuru
1 Emily 30 Bangalore
2 Ramya 28 Mandya
3 Saranya 32 Hassan
In this example, the dictionary data contains three key-value pairs, where the keys
represent the column names, and the corresponding values represent the data in each
column.
The [Link]() function is called with the dictionary as the argument, and the
resulting DataFrame is stored in the variable df.
The DataFrame is then displayed using the print() function.
The DataFrame is created with three columns ('Name', 'Age', 'City'), and each column
contains the data provided in the dictionary. The DataFrame automatically assigns a
numeric index to each row starting from 0.
If the dictionary contains lists or arrays of unequal lengths, Pandas will fill the
missing values with NaN (Not a Number) to ensure a rectangular structure for the
DataFrame.
Creating a DataFrame from tuples in Pandas can be done by passing a list of tuples to
the [Link]() function.
Each tuple represents a row of data, and the elements within the tuple correspond to
the values in each column. Here's an example:
import pandas as pd
data = [
print(df)
In this example, the list data contains three tuples, where each tuple represents a row
of data.
The elements within each tuple correspond to the values in each column.
The [Link]() function is called with the list of tuples as the data argument, and
the columns are specified using the columns parameter.
output:
1 Jane 30 London
2 Mike 28 Paris
OPERATIONS ON DATAFRAMES
You can perform various operations on the DataFrame, such as filtering, grouping,
and manipulation, using the powerful capabilities of Pandas.
Filtering data:
DATA VISUALIZATION
Matplotlib: Matplotlib is a widely used plotting library in Python. It provides a wide range
of plots, including line plots, bar plots, scatter plots, histograms, and more. Here's a simple
example of creating a line plot using Matplotlib
[Link]()
Output:
Pyplot: Pyplot is a sub-module of the Matplotlib library, which is a popular data visualization
library in Python. By importing the pyplot module from Matplotlib, you gain access to a wide
range of functions and methods that allow you to create and manipulate figures, axes, and
different types of charts.
Plotly: Plotly is a powerful library for interactive and web-based data visualization. It offers
a wide range of plots, including line plots, bar plots, scatter plots, 3D plots, and more. Plotly
allows you to create interactive plots that can be embedded in web applications or notebooks.
Here's an example of creating a bar plot using Plotly:
import [Link] as px
# Sample data
data = {
'Category': ['A', 'B', 'C', 'D'],
'Value': [10, 20, 15, 25]
}
HISTOGRAM
LINE CHART
A Line chart is a graph that represents information as a series of data points connected
by a straight line. In line charts, each data point or marker is plotted and connected
with a line or curve.
Example
BAR GRAPHS
When you have categorical data, you can represent it with a bar graph.
A bar graph plots data with the help of bars, which represent value on the y-axis and
category on the x-axis.
Example
import [Link] as plt
x = ['A', 'B', 'C', 'D']
y = [15, 8, 12, 10]
[Link](x, y)
[Link]('Categories')
[Link]('Values')
[Link]('Bar Plot')
[Link]()
PIE CHART
A pie chart represents data as sectors of a circle, where the size of each sector
corresponds to the proportion or percentage it represents.
Pie charts are commonly used to show the composition or relative contribution of
different categories to a whole. They are effective in displaying categorical data and
making comparisons between different categories.
Example
from matplotlib import pyplot as plt
import numpy as np
fig = [Link]()
ax = fig.add_axes([0,0,1,1])
[Link]('equal')
langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,29,12]
[Link](students, labels = langs,autopct='%1.2f%%')
[Link]()