0% found this document useful (0 votes)
9 views

277edb_Dictionaries and OOP in Python

Uploaded by

Muskan Ijaz
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

277edb_Dictionaries and OOP in Python

Uploaded by

Muskan Ijaz
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Dictionaries and OOP

in Python
Introduction to AI
Dictionary in Python
• A dictionary in Python is an unordered collection of data in the form
of key-value pairs. Dictionaries are optimized to retrieve values when
the key is known.
• dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}
Creating a Dictionary
• we can create a dictionary using curly braces {} or the dict() constructor.

• Empty Dictionary:
You can create an empty dictionary using:

empty_dict = {}
Accessing Elements in a Dictionary
• Access a value by referring to its key:
• Use square brackets [] or the get() method to access values.

• The get() method is safer because it returns None if the key doesn’t
exist, whereas using square brackets will raise an error.
Adding, Updating, and Removing
Items in a Dictionary:
• You can add a new key-value pair or update an existing value by
assigning a value to a key.
• Use the del keyword or the pop() method to remove an item.
Iterating Through a Dictionary
• We can use a loop to iterate through the dictionary in different ways.
LIBRARY EXAMPLE:
Dictionary Methods
• keys(): Returns all the keys.
• values(): Returns all the values.
• items(): Returns all key-value pairs.
• update(): Updates the dictionary with key-value pairs from another
dictionary or iterable.
• pop(): Removes the specified key and returns the corresponding
value.
• clear(): Removes all items from the dictionary.
Dictionary Methods Example:
Nested Dictionaries
• A dictionary can contain another dictionary as a value.This is called a
nested dictionary.
• Example:

• Adding items to a nested dictionary:


Combining Two Dictionaries
• We can combine two dictionaries using the update() method or the
new Python 3.9 | operator.
Sorting a Dictionary by Keys or
Values
• Sorting by keys: Use the sorted() function to sort a dictionary by its
keys.
Class Tasks
• Create a Dictionary which Store and Retrieve Student Records.
• Solution:
Class Task:
• Counting Word Frequency in a Sentence
• Solution:
Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm that
uses objects and classes to structure code. It focuses on modeling real-
world entities through objects, making it easier to design, understand,
and maintain large programs.

• Classes: Blueprint for creating objects


• Objects: Instance of a class
• Attributes: Data stored in an object
• Methods: Functions that operate on the data of an object
Access Specifiers:
• In Python, there is no formal concept of access specifiers like in
languages such as C++ or Java (i.e., public, private, protected).
However, Python provides conventions for indicating the accessibility
of class members (variables and methods) using naming conventions.
These conventions aren't enforced by the language but are widely
followed by Python developers.
Public Members
• In Python, all class attributes and methods are public by default. This
means they can be accessed from both inside and outside the class.
Public members are written without any leading underscores.
Private Members:
• To indicate that a member is private (i.e., should not be accessed
directly from outside the class), you prefix its name with two
underscores (__).
• Python uses name mangling for private members. It changes the
name of the member internally to make it harder to access directly.
• Private members can still be accessed using a special syntax (which
isn't recommended).
Private Member

Private members can be accessed like this (though it's discouraged):


print(student._Student__name) # Access private attribute (name mangling)
What is a Class
• A collection of objects with same properties and function is known as
class. A class is used to define the characteristics of the objects.
• Syntax:
OBJECT
• Functions of object:
An object can perform different tasks and actions. The actions that can
be performed by an object are knows as functions. For example. The
object car can perform the following functions:
Start,
Stop,
Accelerate,
Reverse etc.
Object
• An object is an instance of a class. When you create an object, you
are making a specific version of the class with its own set of data.
Examples:
• Question 1: Bank Account Class Create a BankAccount class with the
following attributes: account_number, account_holder, and balance. The
class should have the following methods:
• __init__: Initializes the account with the account number, account holder,
and initial balance.
• deposit: Deposits a specified amount into the account.
• withdraw: Withdraws a specified amount from the account if sufficient
balance is available.
• get_balance: Returns the current balance of the account.
• display_account_info: Displays the account number, account holder, and
balance.
Solution:
Example
• Question 2: Rectangle Class Create a Rectangle class with the
following attributes: length and width. The class should have the
following methods:
• __init__: Initializes the rectangle with the length and width.
• area: Calculates and returns the area of the rectangle.
• perimeter: Calculates and returns the perimeter of the rectangle.
• scale: Scales the rectangle by a specified factor.
• display_dimensions: Displays the length and width of the rectangle.
Solution
Question
• Question 3: Student Class Create a Student class with the following
attributes: name, roll_number, and grades. The class should have the
following methods:
• __init__: Initializes the student with the name, roll number, and grades.
• calculate_gpa: Calculates and returns the GPA of the student based on
the grades.
• add_grade: Adds a new grade for a specified subject.
• display_grades: Displays all the grades of the student.
• display_student_info: Displays the name, roll number, and GPA of the
student.
Solution:
Question
• Question 4: Car Class Create a Car class with the following attributes:
make, model, year, and mileage. The class should have the following
methods:
• __init__: Initializes the car with the make, model, year, and initial mileage.
• drive: Drives the car for a specified number of miles and updates the
mileage.
• display_car_info: Displays the make, model, year, and mileage of the car.
• fill_gas: Fills the gas tank with a specified number of gallons.
• service: Services the car.
Solution
OOP Principle 1: Encapsulation
• Encapsulation refers to bundling the data (attributes) and the
methods that operate on the data into a single unit (class).
• In a Medical Record system, a patient's data (attributes) such as
name, age, and medical history are encapsulated inside a Patient
class. The sensitive data is protected and only accessible through
methods (getters/setters).
Example
OOP Principle 2: Inheritance
• Inheritance allows one class (child) to inherit attributes and methods
from another class (parent). This promotes code reusability.
• Consider a Vehicle Rental System:
• Parent class: Vehicle
• Child classes: Car, Bike, Truck
Example

You might also like