1. What is OOP?
OOP is a programming paradigm based on the concept of "objects", which can contain data and
code: Data in the form of fields (attributes), and code in the form of procedures (methods).
2. Why Use OOP?
• Modularity: Makes code easier to manage and debug.
• Reusability: Objects can be reused in different programs.
• Flexibility: Easier to adapt to changes.
• Real-World Modeling: Maps well to real-world concepts (e.g., a "Car" object).
3. OOP vs Procedural Programming
Procedural Programming (e.g., C, older Object-Oriented Programming
Feature
Python) (OOP)
Focus Functions and Procedures (how to do things) Objects (data and behavior)
Data &
Separated Bundled together in objects
Code
Achieved through classes and
Modularity Achieved primarily through functions
objects
Difficulty Easier for small projects Better for large, complex systems
4. Core OOP Concepts
Classes and Objects
• Class: A blueprint for creating objects (a prototype).
• Object (Instance): An individual instance of a class. The actual entity created from the
blueprint.
Encapsulation
The bundling of data (attributes) and the methods (functions) that operate on the data into
a single unit (a class). It restricts direct access to some of an object's components, which can
prevent accidental modification.
• How it's achieved in Python: By convention, using a single leading underscore (_) for
"protected" members and a double leading underscore (__) for "private" name-mangling.
Inheritance
A mechanism where a new class (subclass/child class) is derived from an existing class
(superclass/parent class). The child class inherits the attributes and methods of the parent
class.
• Benefits: Code reusability and establishing a clear "is-a" relationship (e.g., a Car is a
Vehicle).
Polymorphism
The ability of an object to take on many forms. In Python, this often refers to method
overriding or allowing the same method name to be used for different classes.
• Example: A Vehicle class has a move() method. A Car object's move() method might be
different from a Motorcycle object's move() method.
Abstraction
Hiding the complex implementation details and showing only the essential information to the
user. It helps in managing complexity.
• How it's achieved in Python: Using abstract base classes (abc module) to define an interface
without the implementation.
5. Complete Vehicle Management System Example
Class Hierarchy
• Vehicle (Parent/Base Class): Defines common properties (e.g., make, model, year,
rental_rate).
• Car (Child Class): Inherits from Vehicle, adds specific properties (e.g., num_doors).
• Motorcycle (Child Class): Inherits from Vehicle, adds specific properties (e.g.,
has_sidecar).
• RentalSystem: Manages the inventory of vehicles and rental transactions.
Functions
A function is a group of statements that exist within a program for the purpose of performing
a specific task. This approach is sometimes called divide and conquer because a large task is
divided into several smaller tasks that are easily performed. A program that has been written
with each task in its own function is called a modularized program.
Instead of writing the same sequence of statements over and over, a better way to repeatedly
perform an operation is to write the code for the operation once, then place that code in a function.
You execute the code by calling the function.
A function definition specifies what a function does. You write a function definition only once,
and then you can execute the function as many times as you want.
Function Naming Rules
• The function name cannot be a Python keyword.
• The function name cannot contain spaces.
• The first character must be one of the letters a–z or A–Z or an underscore (_).
• After the first character, the name can contain letters, digits, or underscores.
• Uppercase and lowercase letters are distinct.
• In Python, it is a common convention to use lowercase letters and underscores for function
names (e.g., calculate_area). The function name should describe what the function does.
Parameters and Arguments
A parameter is a variable that is created inside the parentheses in a function header. An argument
is any piece of data that is passed into a function when a function is called.
Local Variables
A local variable is a variable that is created inside a function. A function can use local variables
for temporary storage of data or as a place to hold the result of a calculation.
Scope of a Local Variable
The scope of a local variable is the part of a program in which the variable may be accessed. A
local variable can be accessed only from inside the function in which it was created. This means:
1. A local variable cannot be accessed by statements that are outside the function.
2. Different functions can have local variables with the same name, and the functions will not
interfere with each other.
Passing Arguments to a Function
Passing an argument to a function works like an assignment statement.
Passing Multiple Arguments
When you pass multiple arguments, the arguments are passed to the parameters in the order that
they appear in the function call.
Keyword Arguments
Arguments can also be passed to parameters out of order if you specify which argument is passed
to which parameter.
Value-Returning Functions
A value-returning function is a function that returns a value back to the part of the program that
called it.
The return statement
A function must have a return statement to return a value. The return value is the value that the
expression holds.
Dictionaries
A dictionary is an object that stores a collection of data. Each element in a dictionary has two
parts: a key and a value. You use a key to locate a specific value.
Common use cases
Customer profiles, product-price mapping, model outputs
Sets
A set is an object that stores a collection of data. All elements stored in a set must be unique. Sets
are mutable, which means you can add new elements to them and remove existing elements from
them. Because set elements are stored in no particular order, sets do not support indexing.
Set Comprehension
A set comprehension is a shorthand way of creating a set. Like list comprehensions and dictionary
comprehensions, a set comprehension is a compact expression that usually produces a set faster
than other ways of creating a set.
You can also use an if clause with a set comprehension. For example, suppose a set contains
integers and you want to make a second set that contains only the integers from the first set
that are less than 10.
Built in functions of list
1. to add elements
2. Append()
3. Extend()
4. Insert
Both append and extend add elements at the end of list. key difference between append and extend
is that append add a single element to the end of the list. The entire object passed is added as on
item even if its another list. Whereas extend add multiple elements to the end of the list. it unpacks
the elements and adds each item individually.
Insert can be used to insert a value at any desired position. it expand in size to accommodate the
new item. The item that was previously at specified index and all the items after it are shifted one
position toward the end of the list
Other list functions
1. remove
2. pop
3. index
4. sort
5. reverse
Tuples
A tuple is an immutable sequence. A tuple is like a list, in that it can contain multiple items, but its
contents cannot be changed during the program’s execution.
Creating Tuples
The easiest way to create a tuple is to enclose one or more comma-separated items in parentheses:
my_tuple = (item1, item2)
Note: The parentheses are often optional. However, it is recommended to use parentheses when
creating a tuple.
Tuple support all the operations as list except those that change the content of tuple. Tuple
supports:
• Indexing
• len, min, max
• Slicing
• The in operator
• The + and * operator
Tuples do not support methods such as append, remove, insert, reverse and sort.
Lists
A list is an object that contains multiple data items. Lists are mutable, which means that their
contents can be changed during a program’s execution. Lists are dynamic data structures, meaning
that items may be added to them or removed from them. You can use indexing, slicing, and various
methods to work with lists in a program
A list is called an object because:
It is created from the list class (i.e., numbers = list([...])).
It has attributes and methods you can use — such as .append(), .remove(), .sort(), etc.
Each item that is stored in a list is called an element.
Nested Loops
A loop that is inside another loop is called a nested loop
An inner loop goes through all of its iterations for every single iteration of outer loop
For Loop
The for statement is used to write a count-controlled loop
The for statement is designed to work with a sequence of data items. When the statement executes,
it iterates once for each item in the sequence. Here is the general format:
for variable in [data item, data item, etc.]:
statement
statement
etc.
The range function
The range function generates a sequence of integer. The value returned by the range function can
be thought of as an iterable sequence.
Repetition Structure
A repetition structure causes a statement or set of statements to execute repeatedly. Programmers
commonly have to write code that performs the same task over and over. For example, suppose
you have been asked to write a program that calculates sales commission for several salespeople.
one approach would be to write the code to calculate one salesperson’s commission, and then
repeat that code for each salesperson
Instead of writing the same sequence of statements over and over, a better way to repeatedly
perform an operation is to write the code for the operation once, then place that code in a loop.
Types of Loops
1. While Loop
2. For Loop
While Loop
A while loop is known as a condition-controlled loop. It causes a statement or set of statements to
repeat as long as a condition is true.
The while loop is ideal for situations that cannot be worked with a count-controlled loop. Any
situation that requires the program to wait for a certain event to occur is an ideal place to use a
while loop.
String Comparison/Nested Decision Structure/Logical Operators
String Comparison
Python allows you to compare strings. This allows you to create decision structures that test the
value of a string.
Relational Operators Used to Compare Strings
Operator Meaning
> Greater than
< Less than
== Equal to
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
Nested Decision Structures
Nested decision structures are decision structures that are located inside other decision structures.
Logical Operators
1. and
2. or
3. not
Topic Detail
Basic Output The print() function is used to display output to the user.
The three primary data types covered are: integer (whole numbers),
Data Types float (numbers with a fractional part), and strings (sequences of
characters, enclosed in quotes).
Variables are used to store data in memory. The notebook shows
Variables
examples of assigning values of different types (e.g., a = 2.50, b = 2).
Escape Special character combinations used inside a string to represent
Sequences something that is otherwise difficult or impossible to type:
- \n is used to represent a newline (causes the output cursor to move to
the next line).
- \t is used to represent a tab (inserts a tab space).
Topic Detail
Sequence Statements execute in the order they appear, one after the other. This
Structure is the default flow of execution.
Decision Used to make a program perform a specific action only if a certain
Structure condition holds true. This is achieved using the if statement.
Topic Detail
The simplest form of a decision structure. If the condition following
if Statement if is true, the indented block of code is executed. If false, the code is
skipped.
Practice Question:
1. Write a program that converts speeds from kilometers per hour (KPH) to miles per hour
(MPH). The program should define a starting speed (START_SPEED), an ending speed
(END_SPEED), and a speed increment (INCREMENT). It should also define a conversion
factor (CONVERSION_FACTOR = 0.6214) that will be used to convert KPH to MPH.
The program should then print a table displaying the speeds in both KPH and MPH, where
each row contains the KPH value and its corresponding MPH value.
2. Write a Python program that asks the user to enter positive numbers repeatedly. After each
positive number, it should add it to a running total. The program should stop asking for
input and print the total when the user enters 0 or a negative number.