SlideShare a Scribd company logo
Software Construction &
Development
(Week-4)
Mr. Muhammad Bilal
MS Software Engineering
LECTURER (Department of Software Engineering)
UOL- Lahore
Agenda of Week # 4
 OOP in Python
 Classes
 Objects
 Encapsulation
 Inheritance
 Polymorphism
OOP Revisited in Python
OOP in a Nutshell
 Object-oriented programming (OOP) is a programming language model in
which programs are organized around data, or objects, rather than
functions and logic.
 An object can be defined as a data field that has unique attributes and
behaviour.
 Examples of an object can range from physical entities, such as a human
being that is described by properties like name and address, down to
small computer programs, such as widgets.
 This opposes the historical approach to programming where emphasis
was on how the logic was written rather than how to define the data
within the logic.
OOP in a Nutshell (contd.)
 The first step in OOP is to identify all of the objects a programmer wants
to manipulate and how they relate to each other, an exercise often
known as data modelling.
 Once an object is known, it is generalized as a class of objects that
defines the kind of data it contains and any logic sequences that can
manipulate it. Each distinct logic sequence is known as a method and
objects can communicate with well-defined interfaces called messages.
 OOP focuses on the objects that developers want to manipulate rather
than the logic required to manipulate them. This approach to
programming is well-suited for programs that are large, complex and
actively updated or maintained.
What is a Class?
 A class is a special data type which defines how to build a certain kind of
object.
 The class also stores some data items that are shared by all the instances
of this class.
 Instances are objects that are created which follow the definition given
inside of the class.
 Functions belonging to classes are called methods. Said another way, a
method is a function that is associated with a class, and an instance
variable is a variable that belongs to a class.
What is an Object?
 Objects are the basic run-time entities in an object-oriented system.
 They may represent a run-time instances of a person, a place, a bank
account, a table of data or any item that the program must handle.
 When a program is executed, the objects interact by sending messages to
one another.
 Objects have two components:
 Data (i.e. attributes)
 Behaviors (i.e. methods)
 An object, practically speaking, is a segment of memory (RAM) that
references both data (referred to by instance variables) of various types
and associated functions that can operate on the data.
Python Class
 A class is a collection of objects. A class contains the blueprints or the
prototype from which the objects are being created. It is a logical entity
that contains some attributes and methods.
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.)
operator. Eg.: Myclass.Myattribute
 Conventionally, the first letter of class name is written in capital ‘MyClass’
 #Python3 program to define a class
class Dog:
pass
Python Object
 The object is an entity that has a state and behavior associated with it.
 Integers, strings, floating-point numbers, even arrays, and dictionaries,
are all objects.
 Any single integer or any single string is an object.
 The number 12 is an object, the string “Hello, world” is an object, a list is
an object that can hold other objects, and so on.
 You’ve been using objects all along and may not even realize it.
Python Object
 An object consists of:
 State: It is represented by the attributes of an object. It also reflects the
properties/attributies of an object.
 Behavior: It is represented by the methods of an object. It also reflects
the response of an object to other objects.
 Identity: It gives a unique name to an object and enables one object to
interact with other objects.
Python Object
 To understand the state, behavior, and identity, take the example of the
class dog.
 The identity can be considered as the name of the dog.
 State or Attributes can be considered as the breed, age, or color of the
dog.
 The behavior can be considered as to whether the dog is eating or
sleeping.
 Creating an object in Python
object_of_dog_class = Dog()
Constructor Intro
 The __init__ method is similar to constructors in C++ and Java. It is run as
soon as an object of a class is instantiated. The method is useful to do any
initialization you want to do with your object.
 Instantiating Objects with ‘__init__’
 __init__ is the default constructor
 __init__ serves as a constructor for the class. Usually does some
initialization work
 An __init__ method can take any number of arguments
 However, the first argument self in the definition of __init__ is special
Constructor Syntax
def __init__(self):
# body of the constructor
Constructor in Code
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age:
{self.age}")
# Creating an instance of the Person class
person1 = Person("Alice", 30)
person1.display() # Output: Name: Alice,
Age: 30
# Creating another instance of the Person
class
person2 = Person("Bob", 25)
person2.display() # Output: Name: Bob, Age:
25
Constructor Code Explained
 In the example code onprevious slide, We defined a class named Person.
 The __init__() method serves as the constructor. It takes three parameters: self (a
reference to the current instance), name, and age.
 Inside the constructor, we initialize the name and age attributes of the object using the
values passed to the constructor.
 We also define a method display() to display the name and age of the person.
 We create two instances of the Person class (person1 and person2) by passing different
values for name and age.
 When each instance is created, the __init__() constructor method is automatically
called to initialize the object with the provided values.
 Finally, we call the display() method on each object to print its name and age.
 Constructors are commonly used to initialize the state of objects when they are created.
They can also perform additional setup tasks if needed.
Self
 No, ‘ self ‘ is not a keyword in Python. Self is just a parameter name used
in instance methods to refer to the instance itself.
1. Class methods must have an extra first parameter in the method definition.
We do not give a value for this parameter when we call the method, Python
provides it.
2. If we have a method that takes no arguments, then we still have to have
one argument.
3. This is similar to this pointer in C++ and this reference in Java.
 When we call a method of this object as myobject.method(arg1, arg2),
this is automatically converted by Python into MyClass.method(myobject,
arg1, arg2) – this is all the special self is about.
Python Usage in Different Areas
 Web Development: Frameworks like Django and Flask – Backend
development: Server-side scripting, handling HTTP requests, managing
databases, and implementing business logic.
 Data Science: NumPy and Pandas, SciKit-Learn, MatplotLib, and Seaborn
 Desktop GUI Applications: Tkinter and PyQt
 Machine Learning and Artificial Intelligence: TensorFlow and PyTorch,
Keras, – Natural Language Processing (NLP): NLTK, SpaCy, and Gensim for
processing and analyzing human language data
 Before that C and C++ dominated the software development.
Disadvantages of C/C++:
 No garbage collector causes memory leakages.
 Not great support of built in libraries.
Python:
 Python is dynamically typed and garbage-collected.
 It supports multiple programming paradigms, including structured
(particularly, procedural), object-oriented, and functional programming.
 It is often described as a "batteries included" language due to its
comprehensive standard library.
Python Code Execution Flow
 The Python source code goes through the following steps to generate
an executable code
 Step 1: The Python compiler reads a Python source code or
instruction in the code editor. In this first stage, the execution of the
code starts.
 Step 2: After writing Python code it is then saved as a .py file in our
system. In this, there are instructions written by a Python script for
the system.
 Step 3: In this the compilation stage comes in which source code is
converted into a byte code. Python compiler also checks the syntax
error in this step and generates a .pyc file.
 Step 4: Byte code that is .pyc file is then sent to the Python Virtual
Machine(PVM) which is the Python interpreter. PVM converts the Python
byte code into machine-executable code and in this interpreter reads and
executes the given file line by line. If an error occurs during this
interpretation then the conversion is halted with an error message.
 Step 5: Within the PVM the bytecode is converted into machine code that
is the binary language consisting of 0’s and 1’s. This binary language is only
understandable by the CPU of the system as it is highly optimized for the
machine code.
 Step 6: In the last step, the final execution occurs where the CPU executes
the machine code and the final desired output will come as according to
your program.
PYTHON BASIC SYNTAX
 A variable in Python is a container for storing data values . A create a
variable is created by assigning a value to it. For example:
 x = 5
 y = "John"
 Variables can be sorted into a variety of categories (or data types)
such as numbers (int/float etc), Boolean values (true/false), and
sequences (strings, lists etc).
 A function is a group of linked statements that perform a
certain task. By using functions, we may break our software
into smaller, more manageable modules. Functions
therefore aid us in better structuring and managing our
program as it grows.
 An if statement executes a block of code only if the specified
condition is met.
 When the condition of the if statement is: True - the body of
the if statement executes. False - the body of the if
statement is skipped from execution.
 Syntax
if condition:
# body of if statement
 An if statement executes a block of code only if the specified
condition is met.
 When the condition of the if statement is: True - the body of
the if statement executes. False - the body of the if
statement is skipped from execution.
 Syntax
if condition:
# body of if statement
software construction and development week 3 Python lists, tuples, dictionaries.pptx
 An if statement can have an optional else clause. The else
statement executes if the condition in the if statement
evaluates to False.
 Syntax
if condition:
# body of if statement
else:
# body of else statement
Here, if the condition inside the if statement evaluates to
True - the body of if executes, and the body of else is skipped.
False - the body of else executes, and the body of if is skipped.
software construction and development week 3 Python lists, tuples, dictionaries.pptx
 Python if…elif…else Statement
 When we need to make a choice between more than two
alternatives, we use the if...elif...else statement.
 Syntax
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
software construction and development week 3 Python lists, tuples, dictionaries.pptx
 Python Nested if Statement
 It is possible to include an if statement inside another if statement.
For example
 Syntax
number = 5
# outer if statement
if number >= 0:
# inner if statement
if number == 0:
print('Number is 0')
# inner else statement
else:
print('Number is positive')
# outer else statement
else:
print('Number is negative')
software construction and development week 3 Python lists, tuples, dictionaries.pptx
 Python for Loop Statement
 In Python, a for loop is used to iterate over
sequences such as lists, strings, tuples, etc.
 Syntax
languages = ['Swift', 'Python', 'Go’]
# access elements of the list one by one
for i in languages:
print(i)
 for Loop with Python range()
 the range() function returns a sequence of numbers. For
example,
 Syntax
values = range(4)
Here, range(4) returns a sequence of 0, 1, 2 ,and 3.
 Since the range() function returns a sequence of numbers,
we can iterate over it using a for loop. For example,
# iterate from i = 0 to i = 3
for i in range(4):
print(i)
Python Data Types
Structures/Collections
 Lists
 Python Lists are just like dynamically sized arrays, declared
in other languages (vector in C++ and ArrayList in Java). In
simple language, a list is a collection of things, enclosed in
[ ] and separated by commas.
 Syntax
Var = [“SCD", “6th", “Semester“, 1, 2, 3, 4]
print(Var)
 Here are some of the methods of list objects:
 list.append(x)
 Add an item to the end of the list. Equivalent to a[len(a):] =
[x].
 list.extend(iterable)
 Extend the list by appending all the items from the iterable.
Equivalent to a[len(a):] = iterable.
 list.insert(i, x)
 Insert an item at a given position. The first argument is the
index of the element before which to insert, so a.insert(0, x)
inserts at the front of the list, and a.insert(len(a), x) is
equivalent to a.append(x)
 list.remove(x)
 Remove the first item from the list whose value is equal to
x.
 list.clear()
 Remove all items from the list. Equivalent to del a[:]
 list.pop([i])
 Removes the item at the given position in the list, and
return it. If no index is specified, a.pop() removes and
returns the last item in the list. It raises an IndexError if the
list is empty or the index is outside the list range.
 Lists Slicing
 Consider a Python list, to access a range of elements in that
list, you need to slice it. Slicing is done using the slicing
operator colon (:). With this operator, one can specify where
to start the slicing, where to end, and specify the step. List
slicing returns a new list from the existing list.
 Syntax
Lst[ Initial : End : IndexJump ]
 IndexJump specifies how many elements to skip between
each index in the slice. If IndexJump is positive, it means
you're moving forward through the list; if it's negative, you're
moving backward.
 Lists Slicing
 If IndexJump is positive, you're moving forward through the
list.
 If IndexJump is negative, you're moving backward through
the list.
 If IndexJump is 1 (or not specified), you're selecting
contiguous elements with no skipping.
 Lists Slicing
 The below diagram illustrates the technique of list slicing.
 Lists Slicing (Example Code)
 # Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
 # Display list
print(Lst[1:5])
 Output
[70, 30, 20, 90]
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Show original list
print("Original List:n", List)
print("nSliced Lists: ")
# Display sliced list
print(List[3:9:2])
# Display sliced list
print(List[::2])
# Display sliced list
print(List[::])
Leaving any argument like Initial, End, or
IndexJump blank will lead to the use of
default values i.e. 0 as Initial, length of the
list as End, and 1 as IndexJump.
OUTPUT
Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sliced Lists:
[4, 6, 8]
[1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 Tuple
 A tuple is an immutable sequence of elements.
 This means that once a tuple is created, its elements cannot
be changed, added, or removed.
 Tuples are similar to lists, but unlike lists, tuples are
immutable, meaning they cannot be modified after
creation.
 The sequence of values stored in a tuple can be of any type,
and they are indexed by integers.
 Tuples are created by enclosing a sequence of elements
within parentheses (), separated by commas. For example:
 my_tuple = (1, 2, 3, 4, 5)
 Tuple (Continued)
 Tuples are created by enclosing a sequence of elements within
parentheses (), separated by commas. For example:
 my_tuple = (1, 2, 3, 4, 5)
 Tuples can contain elements of different data types, including
numbers, strings, and even other tuples. They can also be empty:
 mixed_tuple = (1, 'hello', 3.14, (7, 8, 9))
 empty_tuple = ()
 You can access individual elements of a tuple using indexing, just
like with lists:
 print(my_tuple[0]) # Output: 1 –– print(my_tuple[1]) # Output: 2
 Since tuples are immutable, you cannot modify their elements:
 my_tuple[0] = 10 # This will raise a TypeError because tuples are
immutable
 Sets
 A set is an unordered collection with no duplicate elements.
 Basic uses include membership testing and eliminating
duplicate entries.
 Set objects also support mathematical operations like
union, intersection, difference, and symmetric difference.
 Curly braces or the set() function can be used to create sets.
 Sets
 Note: to create an empty set you have to use the built-in set()
function, not {} because using {} will create an empty dictionary
empty_set = set()
my_set = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana’}
print(my_set)
👇 shows that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
 Membership Testing
 ' orange' in basket # fast membership testing
>>>True
'crabgrass' in basket
>>>False
 Dictionaries
 A dictionary in Python is a data structure that stores the
value in key:value pairs.
 Python Dictionary Syntax
dict_var = {key1 : value1, key2 : value2, …..}
 Example
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks’}
print(Dict)
 Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
 Dictionaries
 As of Python version 3.7, dictionaries are ordered and can
not contain duplicate keys.
 Dictionaries are indexed by keys, which can be any
immutable type; strings and numbers can always be keys.
 Tuples can be used as keys if they contain only strings,
numbers, or tuples; if a tuple contains any mutable object
either directly or indirectly, it cannot be used as a key.
 You can’t use lists as keys, since lists can be modified in
place using index assignments, slice assignments, or
methods like append() and extend().
References
1. https://www.geeksforgeeks.org/python-list-slicing/
2. https://docs.python.org/3/tutorial/datastructures.html
Lets Code
HAVE A GOOD DAY !

More Related Content

PPTX
Python-Classes.pptx
PPTX
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
PDF
From Java to Python: beating the Stockholm syndrome
DOCX
These questions will be a bit advanced level 2
PPTX
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
PPTX
PYTHON PPT.pptx
PPTX
Object-Oriented Programming in Python.pptx
PPTX
python programming ppt-230111072927-1c7002a5.pptx
Python-Classes.pptx
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
From Java to Python: beating the Stockholm syndrome
These questions will be a bit advanced level 2
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
PYTHON PPT.pptx
Object-Oriented Programming in Python.pptx
python programming ppt-230111072927-1c7002a5.pptx

Similar to software construction and development week 3 Python lists, tuples, dictionaries.pptx (20)

PPTX
Networking chapter jkl; dfghyubLec 1.pptx
PPTX
Introduction-to-Python face clone using python.pptx
PPTX
Object Oriented Programming in Python.pptx
PDF
Python Viva Interview Questions PDF By ScholarHat
PPTX
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
PDF
C++
PPTX
1 intro
PDF
C++ [ principles of object oriented programming ]
PPT
Object Oriented Language
PPTX
Paradigms.pptx
PPTX
The Awesome Python Class Part-4
PDF
MCA NOTES.pdf
PDF
Object oriented concepts
PPTX
Integrating Python with SQL (12345).pptx
PPT
Chapter 1- Introduction.ppt
PPTX
Object oriented programming in python
PPTX
Python for dummies
PPTX
PRESENTATION ON PYTHON.pptx
PDF
Oops concepts || Object Oriented Programming Concepts in Java
PDF
M.c.a. (sem iv)- java programming
Networking chapter jkl; dfghyubLec 1.pptx
Introduction-to-Python face clone using python.pptx
Object Oriented Programming in Python.pptx
Python Viva Interview Questions PDF By ScholarHat
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
C++
1 intro
C++ [ principles of object oriented programming ]
Object Oriented Language
Paradigms.pptx
The Awesome Python Class Part-4
MCA NOTES.pdf
Object oriented concepts
Integrating Python with SQL (12345).pptx
Chapter 1- Introduction.ppt
Object oriented programming in python
Python for dummies
PRESENTATION ON PYTHON.pptx
Oops concepts || Object Oriented Programming Concepts in Java
M.c.a. (sem iv)- java programming
Ad

Recently uploaded (20)

PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Digital Strategies for Manufacturing Companies
PDF
AI in Product Development-omnex systems
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
top salesforce developer skills in 2025.pdf
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
medical staffing services at VALiNTRY
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
ai tools demonstartion for schools and inter college
PDF
Understanding Forklifts - TECH EHS Solution
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Transform Your Business with a Software ERP System
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
How Creative Agencies Leverage Project Management Software.pdf
Digital Strategies for Manufacturing Companies
AI in Product Development-omnex systems
Design an Analysis of Algorithms II-SECS-1021-03
Which alternative to Crystal Reports is best for small or large businesses.pdf
top salesforce developer skills in 2025.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
medical staffing services at VALiNTRY
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
CHAPTER 2 - PM Management and IT Context
How to Migrate SBCGlobal Email to Yahoo Easily
ai tools demonstartion for schools and inter college
Understanding Forklifts - TECH EHS Solution
2025 Textile ERP Trends: SAP, Odoo & Oracle
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Transform Your Business with a Software ERP System
Operating system designcfffgfgggggggvggggggggg
Design an Analysis of Algorithms I-SECS-1021-03
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Ad

software construction and development week 3 Python lists, tuples, dictionaries.pptx

  • 1. Software Construction & Development (Week-4) Mr. Muhammad Bilal MS Software Engineering LECTURER (Department of Software Engineering) UOL- Lahore
  • 2. Agenda of Week # 4  OOP in Python  Classes  Objects  Encapsulation  Inheritance  Polymorphism
  • 4. OOP in a Nutshell  Object-oriented programming (OOP) is a programming language model in which programs are organized around data, or objects, rather than functions and logic.  An object can be defined as a data field that has unique attributes and behaviour.  Examples of an object can range from physical entities, such as a human being that is described by properties like name and address, down to small computer programs, such as widgets.  This opposes the historical approach to programming where emphasis was on how the logic was written rather than how to define the data within the logic.
  • 5. OOP in a Nutshell (contd.)  The first step in OOP is to identify all of the objects a programmer wants to manipulate and how they relate to each other, an exercise often known as data modelling.  Once an object is known, it is generalized as a class of objects that defines the kind of data it contains and any logic sequences that can manipulate it. Each distinct logic sequence is known as a method and objects can communicate with well-defined interfaces called messages.  OOP focuses on the objects that developers want to manipulate rather than the logic required to manipulate them. This approach to programming is well-suited for programs that are large, complex and actively updated or maintained.
  • 6. What is a Class?  A class is a special data type which defines how to build a certain kind of object.  The class also stores some data items that are shared by all the instances of this class.  Instances are objects that are created which follow the definition given inside of the class.  Functions belonging to classes are called methods. Said another way, a method is a function that is associated with a class, and an instance variable is a variable that belongs to a class.
  • 7. What is an Object?  Objects are the basic run-time entities in an object-oriented system.  They may represent a run-time instances of a person, a place, a bank account, a table of data or any item that the program must handle.  When a program is executed, the objects interact by sending messages to one another.  Objects have two components:  Data (i.e. attributes)  Behaviors (i.e. methods)  An object, practically speaking, is a segment of memory (RAM) that references both data (referred to by instance variables) of various types and associated functions that can operate on the data.
  • 8. Python Class  A class is a collection of objects. A class contains the blueprints or the prototype from which the objects are being created. It is a logical entity that contains some attributes and methods.  Classes are created by keyword class.  Attributes are the variables that belong to a class.  Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute  Conventionally, the first letter of class name is written in capital ‘MyClass’  #Python3 program to define a class class Dog: pass
  • 9. Python Object  The object is an entity that has a state and behavior associated with it.  Integers, strings, floating-point numbers, even arrays, and dictionaries, are all objects.  Any single integer or any single string is an object.  The number 12 is an object, the string “Hello, world” is an object, a list is an object that can hold other objects, and so on.  You’ve been using objects all along and may not even realize it.
  • 10. Python Object  An object consists of:  State: It is represented by the attributes of an object. It also reflects the properties/attributies of an object.  Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.  Identity: It gives a unique name to an object and enables one object to interact with other objects.
  • 11. Python Object  To understand the state, behavior, and identity, take the example of the class dog.  The identity can be considered as the name of the dog.  State or Attributes can be considered as the breed, age, or color of the dog.  The behavior can be considered as to whether the dog is eating or sleeping.  Creating an object in Python object_of_dog_class = Dog()
  • 12. Constructor Intro  The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.  Instantiating Objects with ‘__init__’  __init__ is the default constructor  __init__ serves as a constructor for the class. Usually does some initialization work  An __init__ method can take any number of arguments  However, the first argument self in the definition of __init__ is special
  • 13. Constructor Syntax def __init__(self): # body of the constructor
  • 14. Constructor in Code class Person: def __init__(self, name, age): self.name = name self.age = age def display(self): print(f"Name: {self.name}, Age: {self.age}") # Creating an instance of the Person class person1 = Person("Alice", 30) person1.display() # Output: Name: Alice, Age: 30 # Creating another instance of the Person class person2 = Person("Bob", 25) person2.display() # Output: Name: Bob, Age: 25
  • 15. Constructor Code Explained  In the example code onprevious slide, We defined a class named Person.  The __init__() method serves as the constructor. It takes three parameters: self (a reference to the current instance), name, and age.  Inside the constructor, we initialize the name and age attributes of the object using the values passed to the constructor.  We also define a method display() to display the name and age of the person.  We create two instances of the Person class (person1 and person2) by passing different values for name and age.  When each instance is created, the __init__() constructor method is automatically called to initialize the object with the provided values.  Finally, we call the display() method on each object to print its name and age.  Constructors are commonly used to initialize the state of objects when they are created. They can also perform additional setup tasks if needed.
  • 16. Self  No, ‘ self ‘ is not a keyword in Python. Self is just a parameter name used in instance methods to refer to the instance itself. 1. Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it. 2. If we have a method that takes no arguments, then we still have to have one argument. 3. This is similar to this pointer in C++ and this reference in Java.  When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about.
  • 17. Python Usage in Different Areas  Web Development: Frameworks like Django and Flask – Backend development: Server-side scripting, handling HTTP requests, managing databases, and implementing business logic.  Data Science: NumPy and Pandas, SciKit-Learn, MatplotLib, and Seaborn  Desktop GUI Applications: Tkinter and PyQt  Machine Learning and Artificial Intelligence: TensorFlow and PyTorch, Keras, – Natural Language Processing (NLP): NLTK, SpaCy, and Gensim for processing and analyzing human language data
  • 18.  Before that C and C++ dominated the software development. Disadvantages of C/C++:  No garbage collector causes memory leakages.  Not great support of built in libraries.
  • 19. Python:  Python is dynamically typed and garbage-collected.  It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented, and functional programming.  It is often described as a "batteries included" language due to its comprehensive standard library.
  • 21.  The Python source code goes through the following steps to generate an executable code  Step 1: The Python compiler reads a Python source code or instruction in the code editor. In this first stage, the execution of the code starts.  Step 2: After writing Python code it is then saved as a .py file in our system. In this, there are instructions written by a Python script for the system.  Step 3: In this the compilation stage comes in which source code is converted into a byte code. Python compiler also checks the syntax error in this step and generates a .pyc file.
  • 22.  Step 4: Byte code that is .pyc file is then sent to the Python Virtual Machine(PVM) which is the Python interpreter. PVM converts the Python byte code into machine-executable code and in this interpreter reads and executes the given file line by line. If an error occurs during this interpretation then the conversion is halted with an error message.  Step 5: Within the PVM the bytecode is converted into machine code that is the binary language consisting of 0’s and 1’s. This binary language is only understandable by the CPU of the system as it is highly optimized for the machine code.  Step 6: In the last step, the final execution occurs where the CPU executes the machine code and the final desired output will come as according to your program.
  • 24.  A variable in Python is a container for storing data values . A create a variable is created by assigning a value to it. For example:  x = 5  y = "John"  Variables can be sorted into a variety of categories (or data types) such as numbers (int/float etc), Boolean values (true/false), and sequences (strings, lists etc).
  • 25.  A function is a group of linked statements that perform a certain task. By using functions, we may break our software into smaller, more manageable modules. Functions therefore aid us in better structuring and managing our program as it grows.
  • 26.  An if statement executes a block of code only if the specified condition is met.  When the condition of the if statement is: True - the body of the if statement executes. False - the body of the if statement is skipped from execution.  Syntax if condition: # body of if statement
  • 27.  An if statement executes a block of code only if the specified condition is met.  When the condition of the if statement is: True - the body of the if statement executes. False - the body of the if statement is skipped from execution.  Syntax if condition: # body of if statement
  • 29.  An if statement can have an optional else clause. The else statement executes if the condition in the if statement evaluates to False.  Syntax if condition: # body of if statement else: # body of else statement Here, if the condition inside the if statement evaluates to True - the body of if executes, and the body of else is skipped. False - the body of else executes, and the body of if is skipped.
  • 31.  Python if…elif…else Statement  When we need to make a choice between more than two alternatives, we use the if...elif...else statement.  Syntax if condition1: # code block 1 elif condition2: # code block 2 else: # code block 3
  • 33.  Python Nested if Statement  It is possible to include an if statement inside another if statement. For example  Syntax number = 5 # outer if statement if number >= 0: # inner if statement if number == 0: print('Number is 0') # inner else statement else: print('Number is positive') # outer else statement else: print('Number is negative')
  • 35.  Python for Loop Statement  In Python, a for loop is used to iterate over sequences such as lists, strings, tuples, etc.  Syntax languages = ['Swift', 'Python', 'Go’] # access elements of the list one by one for i in languages: print(i)
  • 36.  for Loop with Python range()  the range() function returns a sequence of numbers. For example,  Syntax values = range(4) Here, range(4) returns a sequence of 0, 1, 2 ,and 3.  Since the range() function returns a sequence of numbers, we can iterate over it using a for loop. For example, # iterate from i = 0 to i = 3 for i in range(4): print(i)
  • 38.  Lists  Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). In simple language, a list is a collection of things, enclosed in [ ] and separated by commas.  Syntax Var = [“SCD", “6th", “Semester“, 1, 2, 3, 4] print(Var)
  • 39.  Here are some of the methods of list objects:  list.append(x)  Add an item to the end of the list. Equivalent to a[len(a):] = [x].  list.extend(iterable)  Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.  list.insert(i, x)  Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x)
  • 40.  list.remove(x)  Remove the first item from the list whose value is equal to x.  list.clear()  Remove all items from the list. Equivalent to del a[:]  list.pop([i])  Removes the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. It raises an IndexError if the list is empty or the index is outside the list range.
  • 41.  Lists Slicing  Consider a Python list, to access a range of elements in that list, you need to slice it. Slicing is done using the slicing operator colon (:). With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list.  Syntax Lst[ Initial : End : IndexJump ]  IndexJump specifies how many elements to skip between each index in the slice. If IndexJump is positive, it means you're moving forward through the list; if it's negative, you're moving backward.
  • 42.  Lists Slicing  If IndexJump is positive, you're moving forward through the list.  If IndexJump is negative, you're moving backward through the list.  If IndexJump is 1 (or not specified), you're selecting contiguous elements with no skipping.
  • 43.  Lists Slicing  The below diagram illustrates the technique of list slicing.
  • 44.  Lists Slicing (Example Code)  # Initialize list Lst = [50, 70, 30, 20, 90, 10, 50]  # Display list print(Lst[1:5])  Output [70, 30, 20, 90] # Initialize list List = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Show original list print("Original List:n", List) print("nSliced Lists: ") # Display sliced list print(List[3:9:2]) # Display sliced list print(List[::2]) # Display sliced list print(List[::]) Leaving any argument like Initial, End, or IndexJump blank will lead to the use of default values i.e. 0 as Initial, length of the list as End, and 1 as IndexJump. OUTPUT Original List: [1, 2, 3, 4, 5, 6, 7, 8, 9] Sliced Lists: [4, 6, 8] [1, 3, 5, 7, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • 45.  Tuple  A tuple is an immutable sequence of elements.  This means that once a tuple is created, its elements cannot be changed, added, or removed.  Tuples are similar to lists, but unlike lists, tuples are immutable, meaning they cannot be modified after creation.  The sequence of values stored in a tuple can be of any type, and they are indexed by integers.  Tuples are created by enclosing a sequence of elements within parentheses (), separated by commas. For example:  my_tuple = (1, 2, 3, 4, 5)
  • 46.  Tuple (Continued)  Tuples are created by enclosing a sequence of elements within parentheses (), separated by commas. For example:  my_tuple = (1, 2, 3, 4, 5)  Tuples can contain elements of different data types, including numbers, strings, and even other tuples. They can also be empty:  mixed_tuple = (1, 'hello', 3.14, (7, 8, 9))  empty_tuple = ()  You can access individual elements of a tuple using indexing, just like with lists:  print(my_tuple[0]) # Output: 1 –– print(my_tuple[1]) # Output: 2  Since tuples are immutable, you cannot modify their elements:  my_tuple[0] = 10 # This will raise a TypeError because tuples are immutable
  • 47.  Sets  A set is an unordered collection with no duplicate elements.  Basic uses include membership testing and eliminating duplicate entries.  Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.  Curly braces or the set() function can be used to create sets.
  • 48.  Sets  Note: to create an empty set you have to use the built-in set() function, not {} because using {} will create an empty dictionary empty_set = set() my_set = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana’} print(my_set) 👇 shows that duplicates have been removed {'orange', 'banana', 'pear', 'apple'}  Membership Testing  ' orange' in basket # fast membership testing >>>True 'crabgrass' in basket >>>False
  • 49.  Dictionaries  A dictionary in Python is a data structure that stores the value in key:value pairs.  Python Dictionary Syntax dict_var = {key1 : value1, key2 : value2, …..}  Example Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks’} print(Dict)  Output: {1: 'Geeks', 2: 'For', 3: 'Geeks'}
  • 50.  Dictionaries  As of Python version 3.7, dictionaries are ordered and can not contain duplicate keys.  Dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.  Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key.  You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
  • 54. HAVE A GOOD DAY !