0% found this document useful (0 votes)
1 views52 pages

Python For Data Science

The document provides an overview of Python fundamentals for data science, covering basic data types, variables, operators, and complex data structures. It explains how to declare and assign values to variables, the different data types available in Python, and the usage of operators for various operations. Additionally, it introduces complex data structures like stacks, queues, and linked lists, along with examples of their implementation in Python.

Uploaded by

gopika.p.it
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views52 pages

Python For Data Science

The document provides an overview of Python fundamentals for data science, covering basic data types, variables, operators, and complex data structures. It explains how to declare and assign values to variables, the different data types available in Python, and the usage of operators for various operations. Additionally, it introduces complex data structures like stacks, queues, and linked lists, along with examples of their implementation in Python.

Uploaded by

gopika.p.it
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SCSB3018- Python for Data Science

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

UNIT-I SCSB3018 – Python for Data Science


PYTHON FUNDAMENTALS

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.

Assigning value to variables:

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.:

Fig 1.1. Example of Variable Declaration and Assignment

1.2 Python Data Types


The variable sets aside a stored in memory to store a value, and when it is given a value, that
value is stored in that stored. Now, what kind of data that variable is linked to determines how
much memory it takes up. In other words, the data types tell you how much memory you need
to store the value. The data types in python is shown in Table 1.2.

Table 1.2. Python Data Types


Data Type Category Description
Numbers int, float, numeric values
complex
String Str sequence of characters
Sequence List, tuple sequence of items
Mapping Dict data in key-value pair
Set Set collection of unique items
Python has 5 standard data types:
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
6. Set
Numbers

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.

There are three numbers in Python:

Example:

A = 20 # Assing 20 to A

B = 4.67 # Assign 4.67 to B

print(A) # prints 20 on screen

print(B) # prints 4.65 on screen

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:

S = "Happy" # Assigning a string to variable S

print(S) # Prints the whole string

print(S[0]) # Prints the first character (indexing starts at 0)

print(S + " Morning") # Concatenates and prints "Happy Morning"

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.

❖ Set Data Type:

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.

❖ Boolean Data Type:

The datatype which returns only 2 values either TURE or FALSE.

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

2. Comparison (Relational) Operators


3. Assignment Operators

4. Logical Operators

5. Bitwise Operators

6. Membership Operators

Arithmetic Operators

Common mathematical operations in addition modules are addition, subtraction,


multiplication, and division; additional arithmetic operations include exponential and floor
divisions are shown in Table 3.3. Expressions, variables, and integers are supported by all.
Table 2.1. Arithmetic Operations in Python

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.

Table 2.2. Comparison Operations in Python


Operator Description Python Expression

== Equal x == y

!= Not Equal x != y

> Greater Than x>y

< Less Than x<y


Greater Than or
>= Equal x >= y

<= Less Than or Equal x <= y


Example:

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.

Table 2.3. Assignment Operations in Python


Operator Description Python Expression
= Equal x = y x=x+5
x= 2 * x + 4 * 5 + 8
Example:
Output:

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

4. Complex Data Structures:

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.

PUSH into a Stack

class Stack:

def __init__(self):

[Link] = []

def add(self, dataval):

# Use list append method to add element

if dataval not in [Link]:

[Link](dataval)

return True

else:

return False

# Use peek to look at the top of the stack

def peek(self):

if len([Link]) > 0:

return [Link][-1]

else:

return "Stack is empty"

# Create a Stack object

AStack = Stack()

# Add elements to the stack

[Link]("Mon")
[Link]("Tue")

# Peek the top of the stack

print("Top of the stack:", [Link]()) # Output: Tue

[Link]("Wed")

[Link]("Thu")

# Peek again

print("Top of the stack:", [Link]()) # Output: Thu

Output:

Top of the stack: Tue

Top of the stack: Thu

POP from a Stack

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] = []

def add(self, dataval):

# Use list append method to add element

if dataval not in [Link]:

[Link](dataval)

return True

else:

return False

def remove(self):

# Use list pop method to remove element

if len([Link]) <= 0:
return "No element in the Stack"

else:

return [Link]()

# Creating stack object

AStack = Stack()

# Adding elements

[Link]("Mon")

[Link]("Tue")

[Link]("Wed")

[Link]("Thu")

# Removing and printing elements

print([Link]()) # Should print "Thu"

print([Link]()) # Should print "Wed"

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.

What is a Linked 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.

Types of Linked Lists

• 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.

In this note, we focus mainly on Singly Linked Lists.

Creating a Simple Linked List

To create a linked list, we define two classes:


• Node: Represents each element in the list.
• SLinkedList: Manages the linked list operations.

class Node:

def __init__(self, dataval=None):

[Link] = dataval

[Link] = None

class SLinkedList:

def __init__(self):

[Link] = None

list1 = SLinkedList()

[Link] = Node("Mon")

e2 = Node("Tue")

e3 = Node("Wed")

# Linking the nodes

[Link] = e2

[Link] = e3

Traversing a Linked List

To display all elements in the linked list, we traverse it from the head node to the end.

class Node:

def __init__(self, dataval=None):

[Link] = dataval

[Link] = None

class SLinkedList:

def __init__(self):

[Link] = None

def listprint(self):

printval = [Link]

while printval is not None:


print([Link])

printval = [Link]

list = SLinkedList()

[Link] = Node("Mon")

e2 = Node("Tue")

e3 = Node("Wed")

# Linking the nodes

[Link] = e2

[Link] = e3

[Link]()

Output:

Mon

Tue

Wed

Inserting Elements in a Linked List

1. Inserting at the Beginning

To insert a new node at the beginning:

• Create a new node.


• Set its nextval to the current head.
• Update the head to this new node.

class Node:

def __init__(self, dataval=None):

[Link] = dataval

[Link] = None

class SLinkedList:

def __init__(self):

[Link] = None

def AtBeginning(self, newdata):


NewNode = Node(newdata)

[Link] = [Link]

[Link] = NewNode

def listprint(self):

printval = [Link]

while printval is not None:

print([Link])

printval = [Link]

list = SLinkedList()

[Link] = Node("Mon")

e2 = Node("Tue")

e3 = Node("Wed")

# Linking the nodes

[Link] = e2

[Link] = e3

Output:

Sun

Mon

Tue

Wed

2. Inserting at the End

To insert a new node at the end:

• Traverse to the last node.


• Set its nextval to the new node.

class Node:

def __init__(self, dataval=None):

[Link] = dataval

[Link] = None
class SLinkedList:

def __init__(self):

[Link] = None

def AtEnd(self, newdata):

NewNode = Node(newdata)

if [Link] is None:

[Link] = NewNode

return

laste = [Link]

while [Link]:

laste = [Link]

[Link] = NewNode

def listprint(self):

printval = [Link]

while printval is not None:

print([Link])

printval = [Link]

list = SLinkedList()

[Link] = Node("Mon")

e2 = Node("Tue")

e3 = Node("Wed")

# Linking the nodes

[Link] = e2

[Link] = e3

[Link]("Thu")

[Link]()

Output:

Mon
Tue

Wed

Thu

3. Inserting in Between Two Nodes

To insert a new node after a specific node:

• Ensure the specified node exists.


• Set the new node's nextval to the specified node's nextval.
• Update the specified node's nextval to the new node.

class Node:

def __init__(self, dataval=None):

[Link] = dataval

[Link] = None

class SLinkedList:

def __init__(self):

[Link] = None

def InBetween(self, middle_node, newdata):

if middle_node is None:

print("The mentioned node is absent")

return

NewNode = Node(newdata)

[Link] = middle_node.nextval

middle_node.nextval = NewNode

def listprint(self):

printval = [Link]

while printval is not None:

print([Link])

printval = [Link]

list = SLinkedList()
[Link] = Node("Mon")

e2 = Node("Tue")

e3 = Node("Thu")

# Linking the nodes

[Link] = e2

[Link] = e3

[Link](e2, "Fri")

[Link]()

Output:

Mon

Tue

Fri

Thu

Removing an Element

To remove a node with a specific value:

• Check if the head node contains the value.


• If not, traverse the list to find the node.
• Update the previous node's nextval to skip the node to be deleted.

class Node:

def __init__(self, data=None):

[Link] = data

[Link] = None

class SLinkedList:

def __init__(self):

[Link] = None

def AtBeginning(self, data_in):

NewNode = Node(data_in)

[Link] = [Link]
[Link] = NewNode

def RemoveNode(self, Removekey):

HeadVal = [Link]

if HeadVal is not None:

if [Link] == Removekey:

[Link] = [Link]

HeadVal = None

return

while HeadVal is not None:

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

Tree – A Hierarchical Data Structure

A tree is a non-linear data structure where:

• One element is the root.


• Every node may have children.
• No cycles exist (i.e., you can’t loop back to a parent).

It resembles a family tree or folder structure.

Basic Terms

• Root: Topmost node.


• Child: A node that descends from another node.
• Parent: A node with child nodes.
• Leaf: A node with no children.
• Subtree: A tree formed from a node and its descendants.

Types of Trees

• Binary Tree: Each node has at most 2 children.


• Binary Search Tree (BST): Left child < parent < right child.
• Heap Tree: Maintains a specific ordering property (min-heap or max-heap).
• Decision Tree: Used in ML for classification/regression.

class Node:

def __init__(self, data):

[Link] = data

[Link] = None

[Link] = None

# Create root

root = Node(10)

# Insert left and right children

[Link] = Node(5)
[Link] = Node(15)

print("Root:", [Link])

print("Left child:", [Link])

print("Right child:", [Link])

Output:

Root: 10

Left child: 5

Right child: 15

Graph – A Network of Nodes

A graph is a collection of nodes (vertices) and edges (connections between nodes). Unlike
trees, graphs can have cycles.

Types of Graphs

• Directed Graph (DiGraph): Edges have direction.


• Undirected Graph: Edges are bidirectional.
• Weighted Graph: Edges have weights (cost, distance).
• Unweighted Graph: All edges are equal.
• Cyclic/ Acyclic Graph: Has/doesn’t have cycles.

Representation in Python

• Adjacency List: Dictionary of lists.


• Adjacency Matrix: 2D array.
• Using NetworkX: A powerful library for graph data.

Example Using Dictionary:

graph = {

'A': ['B', 'C'],

'B': ['D'],

'C': ['E'],

'D': [],

'E': ['F'],

'F': []

}
def dfs(graph, node, visited):

if node not in visited:

print(node)

[Link](node)

for neighbour in graph[node]:

dfs(graph, neighbour, visited)

visited = set()

dfs(graph, 'A', visited)

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

• The default mode of execution.


• Statements are executed line by line in the order they appear.

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:

• A conditional statement checks to see if a specific condition exists before executing


code.
• Conditional statements can help increase the performance of your code by giving you
control over the flow of your code, such as when and how it is run.
• This can be quite useful for determining whether a specific condition occurs before the
code begins to execute, as you may want to execute specific code lines only when
criteria are satisfied.
• Conditional statements, for example, can be used to verify the existence of a specific
variable or file before executing code, or to execute more code if certain criteria are
met, such as a calculation yielding a specified result.
TYPES OF CONDITIONAL STATEMENT

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:

# code to run if condition is true

# this code runs after the if block

The if statement in Python is used to check a condition.


If the condition is true, then the code inside the if block will run.
If the condition is false, Python skips the if block and moves to the next line after it.

The flow chart of if statement is shown in Figure.

Fig 4.1. Flow Chart of if Statement

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.

Fig 4.2. Flow Chart of if-else Statement

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:

# 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 none of the above conditions are true

The flow chart of else-if- lader statement is shown in Figure 4.3.

Fig 4.3. Flow Chart of else-if ladder Statement

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.

• The if block runs if the first condition is true.


• If not, Python checks the elif (else-if) conditions one by one.
• If none of the if or elif conditions are true, the else block is executed.

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

if temperature > 35:


print("It's very hot!")
elif temperature > 25:
print("It's warm.")
elif temperature > 15:
print("It's cool.")
else:
print("It's cold.")
Output: It's warm.

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.

TYPES OF LOOP STATEMENTS


As is the case with other programming languages, Python has three distinct types of looping
statements, which are provided in the following order:
• For Loop Statement
• While Loop Statements
• Nested Loop Statement
1. For Loop Statement
It is possible to iterate over a series of elements in Python by using the for loop, which is one
of the looping instructions contained inside the language. There are a variety of objects that
can be iterated, including a list, a tuple, a text, and any other object.

Syntax:

for variable in sequence:

# Code block to be executed

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:

# Code block to be executed

Total 10 time block will be repeated

The flowchart to represent for loop statement in python is shown in Figure 5.2

Fig 5.2. Flowchart of For-loop Statement

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:

range ([start], stop, [step])


Every one of the three arguments must be an integer. The value of the [start] parameter is
always set to zero, unless an alternative number is provided. The only parameter that is required
for the function described above is stop. It is one less than the stop parameter that the last
integer in the series is. In the intervals between, the [step] value, which is set to 1 by default,
is used to increment the numbers.

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:

The syntax of the while loop in Python is given below.

while condition:

# Code block to be executed


A boolean expression called condition in this syntax is evaluated at the beginning of each loop
iteration. The while statement is followed by a code block that is periodically run until the
condition evaluates to False.

The flowchart to represent while loop statement in python is shown in Figure 5.3

Fig 5.3. Flowchart of While-loop Statement

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.

3. Nested Loop Statement

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:

for variable in sequence:

for i_variable in i_sequence:

# Code block to be executed

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 :

The code given below uses the Nested Loop.


Output:

4 . Function Calls

Used to jump to a function block and return back after execution


Example:
def greet():
print("Hello!")

greet() # Function call


Output:
Hello!

[Link] StatementsThe Python control statements that regulate how Looping


Statements flow. Control statements are an essential aspect of any programming language,
including Python.

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.

TYPES OF CONTROL STATEMENTS

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:

The syntax of the break statement in Python is as follows:

for variable in sequence:

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

# Code block to be executed

• 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.

FUNCTIONS And Methods

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 definition is initiated with the def keyword.

• 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.

Fig 10.2. The python function working


TYPES OF FUNCTIONS
There are two types of functions in python which are shown in Figure 10.3:

• User-Defined Functions
• Built-in Functions

Fig10.3. Types of User-defined functions


User-Defined Functions
These functions are defined by the user to carry out any given task. Defining a function allows
you to reuse code, making it more modular and easier to read. In Python, you can define a
function with the def keyword, followed by the function name and any required parameters in
parentheses. The python code that defines the function and is shown in below example.

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:

Table 10.1 Built-in Functions in Python

Function Description

pow() Returns the power of two numbers

abs() Returns the absolute value of a number

max() Returns the largest item in a python iterable

min() Returns the largest item in a python iterable


sum() Sum() in Python returns the sum of all the items in an iterator

type() The type() in Python returns the type of a python object

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

PYTHON LAMBDA FUNCTION

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.

Table 10.2. Lamba Function Vs Non-Lamba Function


With lambda function Without lambda function

Work for single-line statements that Work for multi-line statements inside
return a value. function

Ideal for executing quick tasks or data


manipulations. Ideal for executing multi-line code

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?

A method is a function that belongs to an object. It is called using dot notation.

name = "Suji"

print([Link]()) # Method on string object

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.

Creating a Python Class with Self argument


Class is a combination of set of attributes and methods. However, the methods are useful to
process or perform specific operations over attributes. Classes are created by keyword called
class. The attributes are the variables that belong to a class. Attributes are always public and
can be accessed using the dot (.) operator.
Syntax:
class Class Name:
# Statement-1


….
# Statement-N

Example: class Student:


def __init__(self, name, age,marks):
[Link] = name
[Link] = age
[Link] = marks
s1 = Student("Rama", 15, 80)
s2 = Student(“Krishna”, 12, 60)
print([Link])
print([Link])
print([Link])
In the above example, a class named Student using the class keyword is created with the
attributes name, age and marks. Class is initialized as self with the values of name=Rama,
age=15 and marks=80 with object s1. Finally individual elements related to the student class
are displayed. Similarly, other object s2 was also created and instantiated.

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.

Creating a Python Object


Using this, an object of the class Student, which was declared earlier, will be created with the
name obj. Let's have a fundamental understanding of some terms that will be utilized while
working with objects and classes before we delve into the specifics of objects and classes with
example shown in Figure 13.2.

Fig : A Python Class and Object: Example


Example:

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.

IMPORT PYTHON MODULE


We can import the functions, and classes defined in a module to another module using the
import statement in some other Python source file. When the interpreter encounters an import
statement, it imports the module if the module is present in the search path.
The syntax to import python module is:
import module_name
For example, to import the module [Link], we need to put the following command at the
top of the script. import arithmatic
This does not import the functions or classes directly instead imports the module only. To
access the functions inside the module the dot(.) operator is used.
import arithmetic. add
import arithmetic. sub

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

Module Use Case


math Mathematical operations
random Random number generation
datetime Work with dates and times
os Interact with operating system
sys Work with Python system
Example:

import random

print([Link](1, 10)) # Random number between 1 and 10

Importing Packages in Python for Data Science

What is a Package?

A package is a collection of Python modules grouped together in a directory. It helps


organize code for large-scale projects.

In Data Science, packages like NumPy, Pandas, and Matplotlib contain many useful
modules for data handling, analysis, and visualization.

How to Import a Package?

Python provides multiple ways to import packages:

[Link] entire package

Import numpy

[Link] with alias

import numpy as np

[Link] specific function or module

from numpy import array


4. Import multiple functions

from math import sqrt, pi

Common Packages Used in Data Science

Here's a list of essential packages and how to import them.

1. NumPy

• For numerical computations

import numpy as np

a = [Link]([1, 2, 3])
print([Link]()) # Output: 2.0
2. Pandas

• For data manipulation and analysis

import pandas as pd

data = {'Name': ['A', 'B'], 'Marks': [90, 80]}


df = [Link](data)
print([Link]())
3. Matplotlib

• For plotting graphs and charts

import [Link] as plt

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.

In Data Science, documentation is especially important because:

• 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.

Types of Documentation in Python

1. Inline Comments
Short notes within the code to explain a specific line or block.

Example:

# Import pandas for data manipulation


import pandas as pd
# Load CSV file
df = pd.read_csv('[Link]')
2. Docstrings

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__)

3. Markdown Cells (in Jupyter Notebooks)

Jupyter Notebooks allow mixing code and Markdown (formatted text) for rich explanations,
headings, equations, and images.

Example in Markdown:

Step 1: Load and Explore the Data

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:

• What the project is


• How to run it
• Dependencies
• Data sources
• Outputs

You might also like