0% found this document useful (0 votes)
39 views72 pages

Unit 3

The document discusses various Python data structures including lists, sets, tuples, and dictionaries. It provides examples of how to define, access, and manipulate each type of data structure. For lists, it demonstrates how to iterate through a list using a for loop and access elements using indexes. For sets, it shows how to perform common set operations like union, intersection, difference, and symmetric difference. The document also discusses building custom data structures and provides examples of list slicing and built-in list methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views72 pages

Unit 3

The document discusses various Python data structures including lists, sets, tuples, and dictionaries. It provides examples of how to define, access, and manipulate each type of data structure. For lists, it demonstrates how to iterate through a list using a for loop and access elements using indexes. For sets, it shows how to perform common set operations like union, intersection, difference, and symmetric difference. The document also discusses building custom data structures and provides examples of list slicing and built-in list methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

UNIT-III

Design with classes:


• Getting inside objects and classes
• Data-Modeling Examples
• Building a New Data structure
• The Two-Dimensional grid
• Structuring classes with inheritance and Polymorphism
• Graphical User Interfaces
• The Behavior of terminal-Based programs and GUI Based
programs
• Coding simple GUI Based programs
• Windows and window components
• Command Buttons and responding to events
Classes in Python
• In Python, a class is a user-def ined data type that contains both the
data itself and the methods that may be used to manipulate it.
• classes serve as a template to create objects. They provide the
characteristics and operations that the objects will employ.
• Suppose a class is a prototype of a building. A building contains all
the details about the f loor, rooms, doors, windows, etc. we can make
as many buildings as we want, based on these details. Hence, the
building can be seen as a class, and we can create as many objects
of this class.
Getting inside objects and classes in Python

• In Python, a class can be created by using the keyword class, followed by


the class name. The syntax to create a class is given below.

Syntax

class ClassName:

#statement_suite

each class is associated with a documentation string which can be


accessed by using <class-name>.__doc__. A class contains a statement
suite including fields, constructor, function, etc. definition.
Example
class Person:

def __init__(self, name, age):

# This is the constructor method that is called when creating a new Person object

# It takes two parameters, name and age, and initializes them as attributes of the object

self.name = name

self.age = age

def greet(self):

# This is a method of the Person class that prints a greeting message

print("Hello, my name is " + self.name)


Data-Modeling 
 The process of creating Data Models using the syntax and environment of the Python
programming language is called Data Modelling in Python.

 A Data Model is a data abstraction model that organizes different elements of data and
standardizes the way they relate to one another and to the properties of real-world entities.

 In simple words, Data Modelling in Python is the general process by which this programming
language organizes everything internally and it treats and processes data.

 The Data Model is the building block of Python. Internally Data Model has its design and code
blocks for its implementation. It is composed of entities, and entities are none but the
objects.

 Each entity has its own attributes (properties) and methods(actions) or behavior associated
with it. Each object has three attributes: an identity, a type, and a value.
Importance of Data Modeling in Python 
• Improved Performance

Well-designed data models enhance query performance and reduce data redundancy,
resulting in faster and more efficient data processing.

• Data Integrity

Data modeling defines relationships and constraints, ensuring data consistency and
preventing data corruption.

• Scalability

With a robust data model, it becomes easier to accommodate changing business needs
and effectively scale applications to handle larger datasets.
Types of Data Modeling in Python 
 Conceptual Data Modeling

High-level representation of the system's requirements and the relationships between


different entities.

 Logical Data Modeling

Translates the conceptual model into a more detailed representation, considering


attributes, data types, and relationships.

 Physical Data Modeling

Specifies how the logical model is to be implemented, defining database-specific details


like tables, columns, indexes, etc.
Data Modeling Examples in Python
The best way to picture a data model is to think about a building plan of an architect. An
architectural building plan assists in putting up all subsequent conceptual models, and so does
a data model.

These data modeling examples will clarify how data models and the process of data modeling
highlights essential data and the way to arrange it.
• ER (Entity-Relationship) Model
• Hierarchical Model
• Network Model
• Relational Model
• Object-Oriented Database Model
• Object-Relational Model
1. ER (Entity-Relationship) Model

This model is based on the notion of real-world entities and relationships among them. It creates an
entity set, relationship set, general attributes, and constraints.

Here, an entity is a real-world object; for instance, an employee is an entity in an employee database.
An attribute is a property with value, and entity sets share attributes of identical value. Finally, there is
the relationship between entities.

2. Hierarchical Model

This data model arranges the data in the form of a tree with one root, to which other data is connected.
The hierarchy begins with the root and extends like a tree. This model effectively explains several real-
time relationships with a single one-to-many relationship between two different kinds of data.

For example, one supermarket can have different departments and many aisles. Thus, the ‘root’ node
supermarket will have two ‘child’ nodes of (1) Pantry, (2) Packaged Food.
3. Network Model

This database model enables many-to-many relationships among the connected nodes.
The data is arranged in a graph-like structure, and here ‘child’ nodes can have multiple
‘parent’ nodes. The parent nodes are known as owners, and the child nodes are called
members.

4. Relational Model

This popular data model example arranges the data into tables. The tables have columns
and rows, each cataloging an attribute present in the entity. It makes relationships
between data points easy to identify.

For example, e-commerce websites can process purchases and track inventory using the
relational model.

5. Object-Oriented Database Model

This data model def in es a database as an object collection, or recyclable software


components, with related methods and features. For instance, architectural and
engineering real-time systems used in 3D modeling use this data modeling process.

6. Object-Relational Model

This model is a combination of an object-oriented database model and a relational


database model. Therefore, it blends the advanced functionalities of the object-oriented
model with the ease of the relational data model.The data modeling process helps
organizations to become more data-driven. This starts with cleaning and modeling data.
BUILDING A NEW DATA STRUCTURE

The basic Python data structures in Python include list, set, tuples,
and dictionary. Each of the data structures is unique in its own
way. Data structures are “containers” that organize and group data
according to type.
• List
• sets
• Dictionary
• Tuple
List

• Lists are used to store data of different data types in a sequential manner.

• There are addresses assigned to every element of the list, which is called
as Index.

• The index value starts from 0 and goes on until the last element called the
positive index.

• There is also negative indexing which starts from -1 enabling you to access
elements from the last to first.
List – [] Square brackets
List
list = [‘ram',‘Ashif',‘tamil',‘krishna']
Print numbers using list -Example
list = [2,4,6,8,10]
for i in list:
print(i)

Output:
2
4
6
8
10
Example2:

List=[5,10,15,20,25]

for i in list:

print(i)

List=[“Ram”,”tamil”,”vijay”,”Ashif”]

for i in list:

print(i)
for using list – Example3
list = [‘ram',‘Ashif',‘tamil',‘krishna']
for i in range(len(list)):
print(list[i])
Output:
ram
zhair
tamil
krishna
Example4:
s = []
for i in range(10):
s.append(i * i)
print s
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List slicing in Python-Example

my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])
# elements beginning to 4th
print(my_list[:-5])
# elements 6th to end
print(my_list[5:])
# elements beginning to end
print(my_list[:])
Built-in List Functions & Methods
• Python list method cmp() compares elements of two lists.
Syntax:
cmp(list1, list2)
program
list1, list2 = [123, 'xyz'], [456, 'abc']
print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)
Output:
-1
1
-1
sets
• A set is an unordered collection of items.
• Sets can also be used to perform mathematical set operations like union, intersection,
symmetric difference, etc.
• It will not maintains sequence
• Set object does not support indexing
• Sets in Python can be defined as mutable dynamic collections of immutable unique
elements.
Set operations:
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
print(A | B)
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
Intersection of sets
• # initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
print(A & B)
Output:
{4, 5}
# Difference of two sets # initialize A and B

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A #
print(A - B)
{1, 2, 3}
use difference function on A
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
>>> A.difference(B)
Output:
{1, 2, 3}
B >>> B.difference(A)
Output: {8, 6, 7}

Symmetric difference of two sets
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator

print(A ^ B)

Output: {1, 2, 3, 6, 7, 8}
 add()
 update()
 len()
 remove()
 pop()
 clear()
 del
 union()
1.Add()
• To add one item to a set use the add() method.
• To add more than one item to a set use the update() method.

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)
2. update() :

• The update() method inserts the specified items to the


dictionary.
• The specified items can be a dictionary, or an iterable object
with key value pairs.

thisset = {"apple", "banana", "cherry"}



thisset.update(["orange", "mango", "grapes"])

print(thisset)
3.Len()

Get the Length of a Set To determine how many items a set has,
use the len() method.

Example:

thisset = {"apple", "banana", "cherry"}


print(len(thisset))
4.remove() method:

• thisset = {"apple", "banana", "cherry"}



thisset.remove("banana")

print(thisset)

5.pop() method:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)

6.Del()
The del keyword will delete the set completely:
Example:
thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)
7.Clear()
The clear() method empties the set
Example:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
8.clear()

The clear() method empties the set


Example:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Dictionary
Tuples
• Tuples are used to store multiple items in a single variable.

• Tuple is one of 4 built-in data types in Python used to store collections


of data,.

• A tuple is a collection which is ordered and unchangeable.

• Tuples are written with round brackets.

mytuple = ("apple", "banana", "cherry")


Immutable lists
a=(“ram”,10,20,30)
>>a[0]
‘ram’
>>a[-1]
30
• >>>a[1]=100
• Tuple object does not support item assignment
• >>>del a[1]
• Tuple object does not spport item deletion
Creating a Tuple

• A tuple is created by placing all the items (elements) inside


parentheses (), separated by commas. The parentheses are
optional, however, it is a good practice to use them.

• A tuple can have any number of items and they may be of


different types (integer, float, list, string, etc.).
Creating tuple
1. my_tuple = ()
print(my_tuple)
Output:
()
2. my_tuple = (1, 2, 3)
print(my_tuple)
Output:
(1, 2, 3)
3. my_tuple = (1, "Hello", 3.4)
print(my_tuple)
Output:
(1, 'Hello', 3.4)
4. my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output:
('mouse', [8, 4, 6], (1, 2, 3))
• You can access tuple items by referring to the index number,
inside square brackets:
Print the second item in the tuple:
t = ("apple", "banana", "cherry")
print(t[1])
Output:
banana
• Range of Indexes
we can specify a range of indexes by specifying where to start
and where to end the range.
Return the third, fourth, and fifth item:
t =("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(t[2:5])

Output:
“cherry” “orange” “kiwi”

Note:
The search will start at index 2 (included) and end at index 5 (not
included).
Remember that the first item has index 0.
Change Tuple Values
• Once a tuple is created, you cannot change its values. Tuples are
unchangeable, or immutable as it also is called.
• But there is a workaround. You can convert the tuple into a list,
change the list, and convert the list back into a tuple.
• Convert the tuple into a list to be able to change it:

• x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Output:
("apple", "kiwi", "cherry")
Loop Through a Tuple

thistuple = ("apple", "banana", "cherry")


for x in thistuple:
print(x)
Output:
apple
banana
cherry
Check if Item Exists

• Check if "apple" is present in the tuple:


• thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

• Output:
Yes, 'apple' is in the fruits tuple
Tuple Length
• 
To determine how many items a tuple has,
use the len() method:
• Print the number of items in the tuple:

• thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

3


Add Items

• Once a tuple is created, you cannot add items to it. Tuples


are unchangeable
• You cannot add items to a tuple:
• thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
Tuple Methods
Two built-in methods that can use on tuples

• Count() -count the number of times a specified value occurs in


a tuple
• Index() - Searches the tuple for a specified value and returns
the position of where it was found
Two dimensional Grid
• The term "dimensional grid" might refer to a data structure that
represents a grid or matrix with multiple dimensions.
• EXAMPLE CODE
# Create a 2D grid (3x3)
dimensional grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Accessing elements
print(dimensional grid[0][0]) # Output: 1
print(dimensional grid[1][2]) # Output: 6
EXAMPLE CODE -2
• For more advanced and efficient operations on multi-dimensional arrays,
especially for numerical computations, you might want to use the NumPy library:
import numpy as np

# Create a 2D array using NumPy


dimensional_grid_np = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9] NOTE: NumPy provides a wide range of functions
]) and methods for working with multi-dimensional
arrays efficiently.
# Accessing elements
print(dimensional_grid_np[0, 0]) # Output: 1
print(dimensional_grid_np[1, 2]) # Output: 6

Presentation title 45
2.structuring classes with inheritance and polymorphism

• In object-oriented programming, inheritance and polymorphism


are powerful concepts that allow you to create a hierarchy of
classes and write more flexible and extensible code.

Presentation title 46
Inheritance
• Inheritance is the capability of one class to derive or inherit the properties from
another class. The benefits of inheritance are:

• Inheritance enables us to define a class that takes all the functionality from a parent
class and allows us to add more.

• The new class is called derived (or child) class and the one from which it inherits is
called the base (or parent) class.

• Inheritance allows programmer to create a general or a base class first and then later
extend it to more specialized class. It allows programmer to write better code.

Presentation title 47
• Using inheritance you can use or inherit all the data fields and methods available in your
base class. Later you can add you own methods and data fields, thus inheritance provides
a way to organize code, rather than rewriting it from scratch.
• In object-oriented terminology when class X extend class Y, then Y is called
super/parent/base class and X is called subclass/child/derived class. One point to note
here is that only data fields and method which are not private are accessible by child
classes. Private data fields and methods are accessible only inside the class.
class BaseClass:
Body of base class class
--------------------
--------------------
Class Derivedclass(BaseClass):
Body of derived class
-----------------------
-----------------------

Presentation title 48
Class student:
___________
___________
____________

Class mark(student):
______________
_____________
____________--
Types of inheritance Python
Single Inheritance: 

• Single inheritance enables a derived class to inherit


properties from a single parent class, thus enabling code
reusability and the addition of new features to existing
code.
Program 1 - 
Single Inheritance
class student:
def get(self):
self.name=input("enter name")
self.no=input("enter number")

class mark(student):
def read(self):
self.m1=input("enter mark1")
self.m2=input("enter mark2")
def disp(self):
print(self.name)
print(self.no)
print(self.m1)
print(self.m2)

m=mark()
m.get()
m.read()
m.disp()
Multilevel Inheritance :

In multilevel inheritance, features of the base class and the derived class
are further inherited into the new derived class. This is similar to a
relationship representing a child and a grandfather.
Program 2 - Multilevel
class personal:
def get(self):
self.name=input("Enter name: ")
self.reg=input("Enter Regno: ")
class marks(personal):
def read(self):
self.m1=int(input("Enter Mark 1: "))
self.m2=int(input("Enter Mark 2: "))

class total(marks):
def cal(self):
self.tot=self.m1+self.m2
def disp(self):
print(self.name)
print(self.reg)
print(self.m1)
print(self.m2)
print(self.tot)

t= total()
t.get()
t.read()
t.cal()
t.disp()
Multiple Inheritance:
When a class can be derived from more than one base class
this type of inheritance is called multiple inheritances. In
multiple inheritances, all the features of the base classes are
inherited into the derived class.
Program 3 - Multiple
class personal:
def get(self):
self.name=input("Enter name: ")
self.reg=input("Enter Regno: ")

class marks:
def read(self):
self.m1=int(input("Enter Mark 1: "))
self.m2=int(input("Enter Mark 2: "))

class total(personal,marks):
def cal(self):
self.tot=self.m1+self.m2
def disp(self):
print(self.name)
print(self.reg)
print(self.m1)
print(self.m2)
print(self.tot)

t= total()
t.get()
t.read()
t.cal()
t.disp()
Hybrid Inheritance
Inheritance consisting of multiple types of inheritance is called
hybrid inheritance.
Program 4 - Hybrid
class personal:
def get(self):
self.name=input("Enter name: ")
self.reg=input("Enter Regno: ")

class marks(personal):
def read(self):
self.m1=int(input("Enter Mark 1: "))
self.m2=int(input("Enter Mark 2: "))
class average:
def avg(self):
self.a = (self.m1+self.m2)/2
print(self.a)
class total(marks,average):
def cal(self):
self.tot=self.m1+self.m2
def disp(self):
print(self.name)
print(self.reg)
print(self.m1)
print(self.m2)
print(self.tot)

t= total()
t.get()
t.read()
t.cal()
t.disp()
t.avg()
Polymorphism (“MANY SHAPES”) 
• Polymorphism is an important feature of class definition in Python that is
utilized when you have commonly named methods across classes or
subclasses. This permits functions to use entities of different types at
different times. So, it provides flexibility and loose coupling so that code
can be extended and easily maintained over time.

• This allows functions to use objects of any of these polymorphic classes


without needing to be aware of distinctions across the classes.

• Polymorphism can be carried out through inheritance, with subclasses


making use of base class methods or overriding them.
Presentation title 62
EXAMPLE CODE
Base class (Shape):
•It has an __init__ method to initialize the color attribute.
•It has a method area that is meant to be overridden by subclasses.
•It has a display_info method that prints information about the shape
# Base class
class Shape:
def __init__(self, color):
self.color = color

def area(self):
pass # To be implemented by subclasses

def display_info(self):
print(f"Color: {self.color}, Area: {self.area()}")

Presentation title 63
EXAMPLE CODE
Subclasses (Circle and Rectangle):
•They inherit from the Shape class using class Circle(Shape): and class Rectangle(Shape):.
•They provide their own implementations of the area method.
# Subclass 1
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius

64
EXAMPLE CODE
# Subclass 2
class Rectangle(Shape):
def __init__(self, color, width, height):
super().__init__(color)
self.width = width
self.height = height

def area(self):
return self.width * self.height

Presentation title 65
EXAMPLE CODE
Polymorphic function (print_shape_info):
•It takes a Shape object as a parameter and calls the display_info method.
•This function can work with any subclass of Shape, demonstrating polymorphism.
# Polymorphic function
def print_shape_info(shape):
shape.display_info()

# Example usage
circle = Circle("Red", 5)
rectangle = Rectangle("Blue", 4, 6)

print_shape_info(circle)
print_shape_info(rectangle)

Presentation title 66
3.Graphical use interfaces 

• A Graphical User Interface (GUI) is a type of user interface that allows
users to interact with electronic devices through graphical elements such
as icons, buttons, and windows, rather than text-based interfaces. GUIs
are commonly used in software applications to provide a more user-
friendly and visually intuitive experience.

• In software development, GUIs are often created using frameworks and


libraries that provide tools for designing and implementing graphical
components.

Presentation title 67
Tkinter
Tkinter is the standard GUI (Graphical User Interface) toolkit that comes with Python. It is a built-in library
and is widely used for creating desktop applications with graphical interfaces. Tkinter is based on the Tk
GUI toolkit and provides a set of tools for creating windows, dialogs, buttons, text boxes, and other GUI
elements.

Key points

1. Cross-Platform: Tkinter is cross-platform, meaning that applications developed using Tkinter can run on
various operating systems, including Windows, macOS, and Linux, without modification.

2. Simple and Lightweight: Tkinter is known for its simplicity and ease of use, making it an excellent choice
for beginners in GUI programming. It's lightweight and suitable for small to medium-sized projects.

3. Widgets: Tkinter provides a variety of GUI widgets that can be used to build the user interface of an
application. These include labels, buttons, entry fields, text widgets, canvas, and more.

Presentation title 68
4.Event-Driven Programming: Tkinter follows an event-driven
programming paradigm. User actions, such as clicking a button or
typing in an entry field, trigger events that are handled by callback
functions.
5.Integration with Python: Being part of the Python standard
library, Tkinter integrates seamlessly with Python. It is easy to use
in conjunction with other Python libraries and modules.
6.Open Source: Tkinter is open source and freely available for use
and distribution.
Presentation title 69
Tkinter – EXAMPLE
import tkinter as tk

def on_button_click():
label.config(text="Button Clicked!")

# Create the main window


root = tk.Tk()
root.title("Tkinter Example")

# Create a button
button = tk.Button(root, text="Click me!", command=on_button_click)
button.pack(pady=10)

# Create a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack(pady=10)

# Run the main event loop


root.mainloop()
Presentation title 70
4. The behavior of terminal 
.

behavior of a terminal, also known as a command-line interface (CLI) or command prompt.
on Behaviors of a Terminal:
mand Entry: 
erminals allow users to enter commands by typing them in. These commands are typically text
ased and can perform a variety of tasks, such as f ile manipulation, program execution, or
stem configuration.
pt:
terminal usually displays a prompt, which is a symbol or text indicating that the terminal is
ady to accept a command. The prompt often includes information such as the current directory
the username.
mand Execution:
fter entering a command, pressing Enter executes the command. The terminal then displays
e output of the command if there is any.
ystem Navigation: Presentation title 71
6.Redirection and Pipes:
Users can redirect the output of a command to a f ile or use pipes (|) to send the output of one
command as input to another.
7.Command History:
Terminals typically provide a command history feature, allowing users to navigate through previously
entered commands using the arrow keys or other shortcuts.
8. Keyboard Shortcuts:
Terminals often support keyboard shortcuts for common actions, such as copying and pasting text,
clearing the screen, or interrupting the execution of a command.
9.Scripting and Automation:
Users can create shell scripts or batch f iles to automate sequences of commands, making it easier to
perform repetitive tasks.

Presentation title 72

You might also like