Python For Data Science
Python For Data Science
SCHOOL OF COMPUTING
Basic data types and variables - Operators - Complex data structures - Control flow
- Loops - Functions and methods - Classes Objects - Modules Import packages
Documentation.
Python Variables
A memory location set aside to hold a value is called a variable. Python's variable type is
determined by the values provided to it, unlike other programming languages where variables
need to have their types explicitly stated. Python does not require an explicit declaration in
order to reserve memory.
The type of variable is automatically determined by the interpreter based on the data it holds
or is assigned. The equal sign(=), also referred to as the assignment operator, is used to set a
value for the variable.
The following example demonstrates how to declare variables and give them values and is
shown in Figure 1.1.:
Based on their names, these are the types of data that store numbers: integer, float, and complex.
It can be either an int or a long int.
Example:
A = 20 # Assing 20 to A
Output:
20
4.65
Strings
Strings in Python are groups of characters that are kept in memory together, like an array of
characters. Either a single quote or two double quotes are used to show these characters.
Example:
Output:
Happy
Happy Morning
❖ List
In Python, a list is a sorted list of things separated by commas (,) and enclosed in square
brackets ([]). If you access a Python list using the slicing operator [], you can change the value
of any item in it. A list in Python is like a collection. The main difference is that an array is a
collection of items that are all of the same type, while a list is a collection of items that can be
of different kinds. The Python list can be changed.
Example:
Output:
The code above shows that Person_List has items that are numbers, floats, strings, and long
ints. The result shows that the whole Person_List was shown first. Python Tuple Python tuples
are the same as Python lists. The only difference is that Python tuples are immutable, which
means that you can access the things in them but not change their values. Besides being able
to change, another big difference between tuples and lists is that lists are defined inside square
braces [], while tuples are defined inside parentheses ().\
Tuple
A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists,
but unlike lists, they cannot be changed after their creation (i.e., they are immutable).
Example:
Output:
The code above shows that the items in Person_Tuple are integers, floats, strings, long integers,
and strings. The result shows the full Person_Tuple as the first item. After that The first and
fourth items were printed.
But at the end of the last line, an error is made because the fourth member of the tuple is being
changed. Based on the finding, we can say that tuple items can't be changed, but List data types
can.
Dictionary : A sorted list of key-value pairs is called a dictionary in Python. The dictionary's
entries are key-value pairs separated by commas. The value can always be retrieved if we
know the key, but the opposite is not true. Python dictionaries are therefore designed for data
retrieval. Python dictionaries are defined inside curly braces ({}), and the slicing operator ([
]) is used to access and assign values.
Example:
Output:
We have created a dictionary called week in the example above. In this case, the keys are
Monday, Tuesday, Wednesday, and Thursday, and the values are Monday, Tuesday, Wednesday,
and Thursday. To get the appropriate value, we employ keys. not the other way around, though.
Here, we've used the week dictionary's keys to obtain the data.
Capital_city['Thursday'] retrieves its corresponding value, Thu, since 'Thursday' is the key. But
since 'Thu' is the value assigned to the 'Thursday' key, capital_city['Thu'] raises an error.
A set is an arbitrary grouping of distinct objects. Values inside braces {} and separated by
commas define a set.
Example:
Output:
Here, four integer values have been added to a set called student_id. As sets are collections that
are not ordered, indexing is meaningless. The entire set is shown first. Afterwards, trying to
access the element of the set using the slicing operator [] does not work. Similar to the output
accessing the third item with the error message generated by the index.
Example:
A = 50 ;
Output:
>>> A = = 40
>>> FALSE
3. Operators
Operators are unique symbols or keywords in Python that perform operations on values and
variables. They form the foundation of expressions, which are used to work with data and carry
out calculations. Python has a number of operators, each having a distinct function. The Python
programming language supports the following types of operators:
1. Arithmetic Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
Arithmetic Operators
Python
Operator Description Expression
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponent x ** y
Floor
// Division x // y
Example:
Output:
Once the two variables "x" and "y" are defined, this code does a number of mathematical
operations, including floor division, modulus, addition, subtraction, multiplication, and
division, and reports the results.
Comparison Operators
Python comparison operators are required in order to compare two [Link] produce a
Boolean value (True or False) based on the comparison. The comparison operators in python
is shown in Table 2.2.
== Equal x == y
!= Not Equal x != y
Output:
Assignment Operators
To assign values to Python, utilize the assignment operators. The simplest assignment operator
is the single equal symbol (=). The variable on the operator's left side is given the value on the
operator's right side. The different approaches to use assignment operator in python is shown
in Table 2.3.
Above displays the assignment operators in Python. First, 'x' and 'y' have values of 20 and 10,
respectively. Afterwards, x=25 is the output of applying expression x+5 to x.
Bitwise Operators
Bitwise operators in Python carry out actions on discrete binary integer [Link] operate on
each bit location logically while working with integer binary [Link] bitwise
operations, including AND (&), OR (|), NOT (), XOR (), left shift (), and right shift (>>), are
included in Python.
Logical Operators
Boolean expressions are composed, and their truth values are evaluated using logical
operators in Python. They are necessary for controlling the program's execution flow and for
creating conditional statements. The three fundamental logical operators in Python are AND,
OR, and NOT.
Membership Operators
To determine whether a particular value appears in a series or not, one can utilize Python
membership operators. They simplify the process of figuring out which elements belong in
many types of data structures, including sets, tuples, lists, and strings. The is and is not
operators are the two main membership operators in Python
1. Stack
2. Queue
3. Linked List
4. Tree
5. Graph
In a stack the element inserted last in sequence, will come out first as we can remove only
from the top of the stack. Such feature is known as Last in First Out(LIFO) feature. The
operations of adding and removing the elements is known as PUSH and POP. In the
following program, we implement it as add and remove functions. We declare an empty list
and use the append() and pop() methods, to add and remove the data elements.
class Stack:
def __init__(self):
[Link] = []
[Link](dataval)
return True
else:
return False
def peek(self):
if len([Link]) > 0:
return [Link][-1]
else:
AStack = Stack()
[Link]("Mon")
[Link]("Tue")
[Link]("Wed")
[Link]("Thu")
# Peek again
Output:
As we know, we can remove only the top most data element from the stack, we implement a
python program which does that. The remove function in the following program returns the top
most element. We check the top element by calculating the size of the stack first and then, use
the in-built pop() method to find out the top most element.
class Stack:
def __init__(self):
[Link] = []
[Link](dataval)
return True
else:
return False
def remove(self):
if len([Link]) <= 0:
return "No element in the Stack"
else:
return [Link]()
AStack = Stack()
# Adding elements
[Link]("Mon")
[Link]("Tue")
[Link]("Wed")
[Link]("Thu")
Output:
Thu
Wed
Queue
We are familiar with queue in our day to day life as we wait for a service. The queue data
structure also means the same, where the data elements are arranged in a queue. The uniqueness
of queue lies in the way items are added and removed. The items are allowed at on end, but
removed from the other end. So, it is a First-in-First out method.A queue can be implemented
using python list, where we can use the insert() and pop() methods to add and remove elements.
There is no insertion as data elements are always added at the end of the queue.
Adding Elements
In the below example, we create a queue class, where we implement the First-in-First-Out
method. We use the in-built insert method for adding data elements.
class Queue:
def __init__(self):
[Link] = list()
def addtoq(self, dataval):
# Insert method to add element
if dataval not in [Link]:
[Link](0, dataval)
return True
return False
def size(self):
return len([Link])
TheQueue = Queue()
[Link]("Mon")
[Link]("Tue")
[Link]("Wed")
print([Link]())
OUTPUT: 3
Linked List
A linked list is a sequence of data elements, which are connected together via links. Each data
element contains a connection to another data element in form of a pointer. Python does not
have linked lists in its standard library. We implement the concept of linked lists using the
concept of nodes as discussed in the previous chapter. We have already seen, how we create a
node class and how to traverse the elements of a node. In this chapter, we are going to study
the types of linked lists known as singly linked lists. In this type of data structure, there is only
one link between any two data elements. We create such a list and create additional methods to
insert, update and remove elements from the list.
A linked list is a linear data structure where each element (called a node) is a separate
object. Each node contains:
• Data
• A reference (or pointer) to the next node in the sequence
Unlike arrays, linked lists do not store elements in contiguous memory locations. Instead,
nodes are linked using pointers.
• Singly Linked List: Each node points to the next node. Traversal is only forward.
• Doubly Linked List: Each node has pointers to both the next and the previous node.
• Circular Linked List: The last node points back to the first node, forming a circle.
class Node:
[Link] = dataval
[Link] = None
class SLinkedList:
def __init__(self):
[Link] = None
list1 = SLinkedList()
[Link] = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
[Link] = e2
[Link] = e3
To display all elements in the linked list, we traverse it from the head node to the end.
class Node:
[Link] = dataval
[Link] = None
class SLinkedList:
def __init__(self):
[Link] = None
def listprint(self):
printval = [Link]
printval = [Link]
list = SLinkedList()
[Link] = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
[Link] = e2
[Link] = e3
[Link]()
Output:
Mon
Tue
Wed
class Node:
[Link] = dataval
[Link] = None
class SLinkedList:
def __init__(self):
[Link] = None
[Link] = [Link]
[Link] = NewNode
def listprint(self):
printval = [Link]
print([Link])
printval = [Link]
list = SLinkedList()
[Link] = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
[Link] = e2
[Link] = e3
Output:
Sun
Mon
Tue
Wed
class Node:
[Link] = dataval
[Link] = None
class SLinkedList:
def __init__(self):
[Link] = None
NewNode = Node(newdata)
if [Link] is None:
[Link] = NewNode
return
laste = [Link]
while [Link]:
laste = [Link]
[Link] = NewNode
def listprint(self):
printval = [Link]
print([Link])
printval = [Link]
list = SLinkedList()
[Link] = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
[Link] = e2
[Link] = e3
[Link]("Thu")
[Link]()
Output:
Mon
Tue
Wed
Thu
class Node:
[Link] = dataval
[Link] = None
class SLinkedList:
def __init__(self):
[Link] = None
if middle_node is None:
return
NewNode = Node(newdata)
[Link] = middle_node.nextval
middle_node.nextval = NewNode
def listprint(self):
printval = [Link]
print([Link])
printval = [Link]
list = SLinkedList()
[Link] = Node("Mon")
e2 = Node("Tue")
e3 = Node("Thu")
[Link] = e2
[Link] = e3
[Link](e2, "Fri")
[Link]()
Output:
Mon
Tue
Fri
Thu
Removing an Element
class Node:
[Link] = data
[Link] = None
class SLinkedList:
def __init__(self):
[Link] = None
NewNode = Node(data_in)
[Link] = [Link]
[Link] = NewNode
HeadVal = [Link]
if [Link] == Removekey:
[Link] = [Link]
HeadVal = None
return
if [Link] == Removekey:
break
prev = HeadVal
HeadVal = [Link]
if HeadVal is None:
return
[Link] = [Link]
HeadVal = None
def LListprint(self):
printval = [Link]
while printval:
print([Link])
printval = [Link]
llist = SLinkedList()
[Link]("Mon")
[Link]("Tue")
[Link]("Wed")
[Link]("Thu")
[Link]("Tue")
[Link]()
Output:
Thu
Wed
Mon
Basic Terms
Types of Trees
class Node:
[Link] = data
[Link] = None
[Link] = None
# Create root
root = Node(10)
[Link] = Node(5)
[Link] = Node(15)
print("Root:", [Link])
Output:
Root: 10
Left child: 5
Right child: 15
A graph is a collection of nodes (vertices) and edges (connections between nodes). Unlike
trees, graphs can have cycles.
Types of Graphs
Representation in Python
graph = {
'B': ['D'],
'C': ['E'],
'D': [],
'E': ['F'],
'F': []
}
def dfs(graph, node, visited):
print(node)
[Link](node)
visited = set()
Output:
CONTROL FLOW
Control flow refers to the order in which the statements of a program are executed. It
determines how the Python interpreter moves through the code and makes decisions.
Python uses different control flow structures to manage the execution path:
1. Sequential Execution
2. Conditional Statements
3. Looping Statements
4. Function Calls
5. Control Statements
1. Sequential Execution
Example:
print("Step 1")
print("Step 2")
print("Step 3")
Output:
Step 1
Step 2
Step 3
[Link] Statemen
Conditional statements are an essential part of programming in Python. They allow you to
make decisions based on the values of variables or the result of comparisons. The uses of
control statement in python listed below:
As is the case with other programming languages, Python has four distinct types of conditional
statements, which are provided in the following order:
if Statements :
• if-Else Statements
• elif Statements
• If-Elif-Else Statements
1. If Statements
The if statement in Python is one of the conditional statements that is used the most frequently
in programming languages. In this way, it determines whether or not particular statements are
required to be executed. It performs a check to determine whether a particular condition is
satisfied; if the condition is satisfied, the set of code included within the "if" block will be run;
otherwise, it will not be executed.
Syntax:
if condition:
Example:
Output:
2. if-else statements
The Boolean expression is evaluated by the if-else statement. The code in the "if" block will
be executed if the condition is TRUE; otherwise, the code in the "else" block will be executed.
Syntax:
if condition:
# code to run if condition is true
else:
# code to run if condition is false
The flow chart of if-else statement is shown in Figure 4.2.
Example:
The condition (x<20) is tested twice in the code above. The first time it is run, if it is successful,
a block of code will be executed, as we can see in the output. Finally, the final statement, "This
statement will always be executed," is executed, and this is also clearly displayed in the
output. Nevertheless, the second run condition failed by evaluating x=30, executing the else-
Block of code, and generating the output "X is greater than 20." The final statement, "This
statement will always be executed," is finally carried out and is likewise displayed in the
output.
Output:
3. elif statements
"elif" statements are an additional type of conditional statement in Python. The "elif" statement
checks for multiple conditions only in the event that the supplied condition is false. The sole
distinction between it and a "if-else" expression is that the condition will be checked in "elif"
rather than "else."
Syntax: if condition1:
elif condition2:
elif condition3:
else:
Example:
In the code below, the condition (Obtained_Mark >= Dist_Mark) is tested; if it is successful,
the if-block of code is executed; otherwise, the following succeeding blocks are executed based
on the criteria; otherwise, the else statement and the end statement are executed. The code is
executed four times; the first time the condition is met (i.e., 50 > 40), the message
"Congratulations You Passed Exam" is displayed, and the last statement, "End of the
Program", is printed. However, the second time run condition (65 > 60) is successful and
prints "Congratulations You Passed Exam in First Class" before displaying the last line,
"End of the Program". Similarly, in the third run, the requirement (i.e., 80 > 70) is met, and the
message "Congratulations You Passed Exam in Distinction" is displayed, followed by the
final sentence "End of the Program". During the last run, if the condition (i.e., 30 < 40) is not
met, the else block is activated and the message "Sorry, Better Luck Next Time" is written.
The last statement displayed is "End of the Program".
Example:
Output:
4. if-elif-else statements
The if-elif-else statement in Python is used to check multiple conditions one after another.
This structure avoids writing many nested if statements and keeps the code clean and easy to
read.
Syntax:
if condition1:
# code runs if condition1 is true
elif condition2:
# code runs if condition1 is false and condition2 is true
elif condition3:
# code runs if previous conditions are false and condition3 is true
else:
# code runs if all the above conditions are false
Example:
temperature = 30
2. Looping Statement
It could be necessary to repeat a block of code more than once in some circumstances.
Programming languages offer a variety of loops to handle this issue, which enable a series of
instructions to be repeated until a predetermined condition is satisfied.
Syntax:
Explanation of Syntax
• variable → A temporary name that stores the current item in the sequence during
each loop.
• sequence → A collection of items (like a list, string, or range) that we loop through.
• The indented code block runs once for each item in the sequence
Example:
for i in 10:
The flowchart to represent for loop statement in python is shown in Figure 5.2
Example :
The code that you see above has a for loop that prints each element of the 'list' list on a new
line after iterating over each entry in the list. The output is shown on the next page.
Output:
Example 2:
Output:
Using the code that was just presented, the for loop will iterate over each element in the tuple
that is referred to as 'num' and then display it on a new line. In addition, the sum of each number
was computed, the result was saved in the "sum_nums" variable, and the sum value was
eventually printed out. In the run tuple, a sequence of distinct integers (5,8,7,2) is used, and
the result is "the sum of the numbers is 22"
According to Python, a range object is a sequence of numbers that cannot be changed. When
using a for loop, it is helpful to keep track of the number of times a block is repeated.
You can use the range() method in the following ways:
Example:
The range() method was used instead of a for loop statement in the Python code above. Three
for loop statements in all, each printing a distinct range of numbers according on the inputs
passed to the range () function.
When the first "10" value was entered into range (10) it produced numbers starting at 0 and
ending with 10-1, or 9. A for-loop statement is then given range(1,5), and values are printed
starting at 1 and ending at end 5-1, or 4. Lastly, range(10,50,5) is sent to the for-loop
expression, which outputs values starting at 10 and ending at 50-4, or 45, because step=5.
Output:
2. While Loop Statement
Another Python looping expression used to repeat a block of code until a predetermined
condition is met is the while loop.
Syntax:
while condition:
The flowchart to represent while loop statement in python is shown in Figure 5.3
Example:
Output:
The code block is repeated here by the while loop until the sum variable is less than 5. As we
can see in the output, the sum variable is increased by 1 at each iteration, and the current value
of the sum is printed on a new line.
A loop inside another loop is known as a nested loop in Python. When we wish to loop over a
series of components with several degrees of nesting, we utilize it.
Syntax:
Variable, as used in this syntax, is a temporary variable that, for each iteration of the outer loop,
stores the value of each element in the sequence. Every time the inner loop iterates, the value
of every element in the i_sequence is stored in the i_variable, a temporary variable. Every
element in the inner sequence and every element in the outer sequence is subjected to several
executions of the code block that follows the inner for statement.
Example :
4 . Function Calls
Control statements in Python are used to manage the flow of execution of a program based on
certain conditions. Control statements in Python are a powerful tool for managing the flow of
execution. They allow developers to make decisions based on specific conditions and modify
the normal sequential flow of a program. By using control statements effectively, developers
can write more efficient and effective code.
Python, in addition to loop statements, has three different sorts of control statements, which
are given below. These control statements are used to govern the flow of execution.
• Break Statement
• Continue Statement
• Pass Statement
1. Break Statement
A premature termination of the loop in Python can be accomplished with the help of the break
statement. It is utilized in situations in which we wish to exit the loop prior to it having finished
all of its iterations.
Syntax:
if condition:
break
• The value of each element in the sequence is stored in the variable, which is a temporary
variable, and it is used for each iteration of the loop to save the value.
• The condition is a statement that receives a boolean value and is evaluated at the
beginning of each iteration of the loop. If the condition is found to be true, the break
statement is carried out, therefore bringing an end to the loop.
Example:
The code that you see above has a for loop that outputs each item in the "fruits" list on a new
line after iterating over each item in the list. On the other hand, the break statement is executed,
and the loop is halted when the value of the "fruit" variable is equal to "banana." Output:
2. Continue Statement
Using the continue statement in Python, one can skip the iteration of the loop that is currently
being executed. It is utilized in situations in which we wish to skip a certain component of the
sequence and proceed with the subsequent iteration of the loop onward.
Syntax:
for variable in
sequence: if
condition: continue
• The value of each element in the sequence is stored in the variable, which is a temporary
variable, and it is used for each iteration of the loop to save the value.
• The condition is a statement that receives a boolean value and is evaluated at the
beginning of each iteration of the loop.
Example
Output:
The for loop iterates through each item in the "fruits" list in this example, printing each one
on a new line. Nevertheless, the loop's current iteration is skipped and the continue statement
is executed when the value of the "fruit" variable equals "banana."
2. Pass Statement
The pass statement is used as a placeholder in Python. It is used when we want to write
empty code blocks and want to come back and fill them in later. The syntax of the pass
statement in Python is given below.
Syntax:
for variable in sequence:
pass
Every time the loop iterates, the variable—which is a temporary variable—holds the value of
every element in the sequence.
• An empty code block is created using the pass statement and is subsequently filled in.
Example:
In this example, the pass statement is used to create an empty code block while the for loop
iterates over each element in the "fruits" list.
Python functions help to simplify and organize programming by enabling the creation of
smaller code segments. As a result, code is easier for people to understand when they view it.
Functions improve reusability and reduce repetition in code, which is their primary benefit.
Creating A Function.
When defining a function in Python, we must adhere to the following guidelines and syntax is
shown in figure
• The function name that follows the def keyword is followed by parentheses with the
user-passed arguments and a colon at the end.
• The function's body begins with an indented block on a new line following the addition
of the colon.
• The caller receives a result object from the return statement. Return none is the same
as a return statement without an argument.
Calling a Function
After defining a function in Python, we may call it by using its name followed by parenthesis
containing the function's parameters i.e, greet().When the function greet () is called, the
program's control moves to the function definition. All the code within the function is executed.
Following the function call, program control moves on to the following statement. The
necessary steps are described in the figure 10.2 below.
• User-Defined Functions
• Built-in Functions
Example:
In the above example, the welcome () function is completely user-defined and outputs the
message "Welcome to Python world!". The function is only defined once but has different
types. This demonstrates the value of function reusability. Similarly, we can build any function
to fulfill a certain goal.
Output:
Built-in Functions
Python's built-in functions are already defined. A user must remember the name and parameters
of a certain function. There is no need to redefine these functions because they have already
been [Link] of the widely used built-in functions are given below and shown in Table
10.1:
Function Description
Sqrt() Executes the python built-in to find sqrt of the given number
The following two example python codes shown in below demonstrate the usage of built-in
functions to fulfil the specific task. In the first example python code imported math module
and later performed the two functions pow () and sqrt() operations. The result of each function
is produced on the output.
Example
Output
In Python, a lambda function is a short enough anonymous function that can accept any number
of parameters but has only one expression. Lambda functions are also referred to as
"anonymous functions" because they do not require a named function to be defined.
Here's an example of a simple lambda function for adding two [Link] this example, the
lambda function takes two inputs (x and y) and returns their [Link] use a lambda function,
assign it to a variable and call it like a regular function.
Example:
Output:
Python's map() function accepts a function and a list as its arguments. The function calls itself
"map." The function is invoked with a lambda function and a list, and the function then returns
a new list that contains all of the lambda-modified items that were returned by that function
for each item.
Example:
Output:
In order to apply a function to each individual item in a list, the following is an example of
how to use a lambda function together with the map() function. For the purpose of this
illustration, the lambda function is utilized to square each individual element in the numbers
list, and the map () function is utilized to apply the lambda function to each individual element
of the list. After that, the list of squared values that produced the result is displayed on the
screen.
Work for single-line statements that Work for multi-line statements inside
return a value. function
Using the lambda function might This allows comments and necessary
reduce code readability. function descriptions for good readability.
In this, we seen the Lambda function that is available in Python. An n-th number of arguments
can be passed to a lambda function at the same time. Having said that, it only returns a single
argument at a time. In the above section, we will go over certain lambda functions together
with the Python program code, and we will also provide some examples of these functions. In
addition, we talked about the Lambda function in Python, including the list, and the map
function.
What is a Method?
name = "Suji"
Output: Suji
String Methods:
Method Description
upper() Converts to uppercase
lower() Converts to lowercase
strip() Removes whitespace
replace() Replaces substring
split() Splits string into list
Example:
s = "data science"
print([Link]("data", "AI"))
Output:
AI science
List Methods:
Method Description
append() Add element to end of list
extend() Add multiple elements
pop() Remove and return last element
sort() Sort the list
reverse() Reverse the list
Example:
l = [3, 1, 4]
[Link]()
print(l)
Output:
[1, 3, 4]
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.
To understand the need for creating a class let‟s consider an example, let‟s say you wanted to
track the number of dogs that may have different attributes like breed, and age. If a list is used,
the first element could be the dog‟s breed while the second element could represent its age.
Let‟s suppose there are 100 different dogs, then how would you know which element is
supposed to be which? What if you wanted to add other properties to these dogs? This lacks
organization and it‟s the exact need for classes.
PYTHON OBJECTS
A state and a behavior are both associated with the object, which is an entity. It might be
anything taken from the real world, such as a mouse, keyboard, chair, table, pen, or anything
else. There are many different types of objects, including integers, texts, floating-point
numbers, even arrays, and dictionaries. On a more specific level, an object can be defined as
any single number or any single string.
The following three components are used to compose an object:
• State: The attributes of an object are what are used to represent the state of an object.
At the same time, it reflects the characteristics of an object.
• Behavior: it is exemplified by the techniques that an item possesses. The way in which
a thing reacts to other objects is another aspect that it represents.
• Identity: It provides an object with a name that is distinctly its own and makes it
possible for one object to communicate with other objects.
Let us use the example of the class dog, which was explained earlier, to comprehend the
identification, behavior, and state of the student. A possible interpretation of the identification
is that it is the name of the student. The name, age, and marks of the student are all examples
of attributes that can be the student‟s state. The behavior can be interpreted as indicating
whether the student is reading or writing now.
Output:
In the above example the Person class is defined with the three states which includes Name,
Sex and Profession. The behaviors of the Person class includes work () and study (). After
that two objects known as „Jon‟ and „Jessa‟ are created. The fact that Jessa is a woman and
that she is employed as a software engineer is readily apparent. Jon, on the other hand, who is
a male and a lawyer, is a different story. In this case, both objects are formed from the same
class; nevertheless, their states and behaviors are distinct from one another.
PYTHON MODULE
Python modules, on the other hand, are files that contain code that is very similar to one another.
As a result, a module makes the Python code that defines classes, variables, and functions
easier to understand and use.
Example:
In the above code accessed addition functions with [Link] (4.6) and produced result
add result = 10. Similarly, we can access other two methods and produced results related to
subtraction and multiplication operations.
Build-in Module
import random
What is a Package?
In Data Science, packages like NumPy, Pandas, and Matplotlib contain many useful
modules for data handling, analysis, and visualization.
Import numpy
import numpy as np
1. NumPy
import numpy as np
a = [Link]([1, 2, 3])
print([Link]()) # Output: 2.0
2. Pandas
import pandas as pd
x = [1, 2, 3]
y = [2, 4, 6]
[Link](x, y)
[Link]("Line Chart")
[Link]()
Documentation
In programming, documentation refers to the written descriptions of what your code does,
how it works, and how to use it. It helps others (and your future self) understand and maintain
the code.
• Projects may involve multiple steps (data loading, cleaning, modeling, visualization).
• It helps track assumptions, methods, and decisions.
• Makes notebooks, scripts, and models easier to share and reproduce.
1. Inline Comments
Short notes within the code to explain a specific line or block.
Example:
Docstrings are multi-line comments that describe the purpose of a function, class, or
module. They are written using triple quotes """...""".
Example:
def calculate_mean(numbers):
"""
This function takes a list of numbers
and returns their mean.
"""
return sum(numbers) / len(numbers)
To access docstrings:
print(calculate_mean.__doc__)
Jupyter Notebooks allow mixing code and Markdown (formatted text) for rich explanations,
headings, equations, and images.
Example in Markdown:
We use pandas to load the CSV file and check the first 5 rows.
4. README Files
In data science projects, you often include a [Link] file that explains: