HG NOTES

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 77

Data structure with python 20CS41P

ppypython

UNIT 1
Introduction To Data Structures

The choice of a good data structure makes it possible to perform a variety of


critical operations effectively. An efficient data structure also uses minimum
memory space and execution time to process the structure. A data structure is
not only used for organizing the data. It is also used for processing, retrieving,
and storing data. There are different basic and advanced types of data
structures that are used in almost every program or software system that has
been developed. So we must have good knowledge of data structures.
Need Of Data Structure:
The structure of the data and the synthesis of the algorithm are relative to each other.
Data presentation must be easy to understand so the developer, as well as the user, can
make an efficient implementation of the operation.
Data structures provide an easy way of organising, retrieving, managing, and storing
data.
1. Linear Data Structure
2. Non-Linear Data Structure.
Linear Data Structure:
 Elements are arranged in one dimension, also known as linear dimension.
 Example: lists, stack, queue, etc.
Non-Linear Data Structure
 Elements are arranged in one-many, many-one and many-many dimensions.
 Example: tree, graph, table, etc.

IV SEM CSE 1
Data structure with python 20CS41P
ppypython

Advantages of Using Data Structures


 Efficiency in Data Management: Data structures like trees and hash
tables allow for faster data retrieval and management. ...
 Organized Data: Data structures help in organizing data in memory.
 Resource Optimization: Efficient data structures optimize the use
of system resources.
Disadvantage of Data Structure:
Difficulty in designing and implementing complex data
structures. Limited scalability and flexibility. Complexity in
debugging and testing.
The most common built-in data structures in programming
languages include arrays, linked lists, stacks, queues, trees, and
graphs. Arrays: An array is a collection of elements, each
identified by an index or a key.

User Defined Data Structures in Python:


In computer science, a data structure is a logical way of organizing
data in computer memory so that it can be used effectively. A data
structure allows data to be added, removed, stored and maintained
in a structured manner. Python supports two types of data
structures:
 Non-primitive data types: Python has list, set, and dictionary as
its non-primitive data types which can also be considered its in-

IV SEM CSE 2
Data structure with python 20CS41P
ppypython

built data structures.


 User-defined data structures: Data structures that aren’t supported
by python but can be programmed to reflect the same functionality
using concepts supported by python are user-defined data
structures. There are many data structure that can be implemented
this way:

Python

Tuple1 = ()
print("Initial empty Tuple:
") print(Tuple1)
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of
String: ") print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List:
") print(tuple(list1))
Tuple1 = tuple('Geeks')
print("\nTuple with the use of

IV SEM CSE 3
Data structure with python 20CS41P
ppypython
function: ") print(Tuple1)
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python',
'geek') Tuple3 =
(Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
Output:
Initial Tuple:

empty
()
Tuple with the use of String:
('Geeks', 'For')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python',
'geek'))
Note – The creation of a Python tuple without the use of
parentheses is known as Tuple Packing.
Access Tuple Items
In order to access the tuple items refer to the index number. Use
the index operator [ ] to access an item in a tuple. The index
must be an integer. Nested tuples are accessed using nested
indexing.
The code creates a tuple named ‘tuple1′ with five elements: 1, 2,
3, 4, and
5. Then it prints the first, last, and third last elements of the
tuple using indexing.
Python

tuple1 = tuple([1, 2, 3, 4, 5])


print("First element of tuple")
print(tuple1[0])
print("\nLast element of tuple")

IV SEM CSE 4
Data structure with python 20CS41P
ppypython

print(tuple1[-1])

print("\nThird last element of


tuple") print(tuple1[-3])
Output:
First element of tuple
1
Last element of tuple
5
Third las element of tuple
t
3
Note – To know more about tuples, refer to Python Tuples.
3. Boolean Data Type in Python
Python Data type with one of the two built-in values, True or
False. Boolean objects that are equal to True are truthy (true),
and those equal to False are falsy (false). However non-Boolean
objects can be evaluated in a Boolean context as well and
determined to be true or false. It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans
otherwise python will throw an error.
Example: The first two lines will print the type of the boolean
values True and False, which is <class ‘bool’>. The third line will
cause an error, because true is not a valid keyword in Python.
Python is case-sensitive, which means it distinguishes between
uppercase and lowercase letters.
You need to capitalize the first letter of true to make it a
boolean value.
Python

print(type(True))
print(type(False
))
print(type(true)
)
Output:
<class 'bool'
>
<class 'bool'>
Traceback (most recent call
last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8,
in print(type(true))
NameError: name 'true' is not defined

IV SEM CSE 5
Data structure with python 20CS41P
ppypython

4. Set Data Type in Python


In Python Data Types, a Set is an unordered collection of data
types that is iterable, mutable, and has no duplicate elements.
The order of elements
in a set is undefined though it may consist of various elements.

IV SEM CSE 6
Data structure with python 20CS41P
ppypython

Create a Set in Python


Sets can be created by using the built-in set() function with an
iterable object or a sequence by placing the sequence inside curly
braces, separated by a ‘comma’. The type of elements in a set
need not be the same, various mixed-up data type values can
also be passed to the set.
Example: The code is an example of how to create sets using
Python

set1 = set()
print("Initial blank Set:
") print(set1)
set1 = set("GeeksForGeeks")
print("\nSet with the use of
String: ") print(set1)
set1 = set(["Geeks", "For",
"Geeks"]) print("\nSet with the
use of List: ") print(set1)
set1 = set([1, 2, 'Geeks', 4, 'For', 6,
'Geeks']) print("\nSet with the use of Mixed
Values")
print(set1)
Output:
Initial blank
Set: set()
Set with the use of
String:
{'F', 'o', 'G', 's', 'r', 'k', 'e'
}
Set with the use of
List:
{'Geeks', 'For'
}
Set with the use of Mixed
Values
{1, 2, 4, 6, 'Geeks', 'For'}
Access Set Items
Set items cannot be accessed by referring to an index, since
sets are unordered the items have no index. But you can loop
through the set items using a for loop, or ask if a specified value
is present in a set, by using the in the keyword.
Example: This Python code creates a set named set1 with
the values “Geeks”, “For” and “Geeks”. The code then prints the
initial set, the elements of the set in a loop, and checks if the
value “Geeks” is in the
IV SEM CSE 7
Data structure with python 20CS41P
ppypython
set using the ‘in’ operator
Python

set1 = set(["Geeks", "For",


"Geeks"]) print("\nInitial set")
print(set1) print("\
nElements of set: ")

IV SEM CSE 8
PYTHON PROGRAMMING 20CS31P

for i in set1:
print(i, end=" ")
print("Geeks" in
set1)
Output:
Initial

set:
{'Geeks', 'For'
}
Elements of
set:
Geeks

For
True
Note – To know more about sets, refer to Python Sets.
5. Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values,
used to store data values like a map, unlike other Python Data
Types that hold only a single value as an element, a Dictionary
holds a key: value pair. Key- value is provided in the dictionary to
make it more optimized. Each key- value pair in a Dictionary is
separated by a colon : , whereas each key is separated by a
‘comma’.
Create a Dictionary in Python
In Python, a Dictionary can be created by placing a sequence of
elements within curly {} braces, separated by ‘comma’. Values in
a dictionary can be of any datatype and can be duplicated,
whereas keys can’t be repeated and must be immutable. The
dictionary can also be created by the built-in function dict(). An
empty dictionary can be created by just placing it in curly
braces{}. Note – Dictionary keys are case sensitive, the same
name but different cases of Key will be treated distinctly.
Example: This code creates and prints a variety of dictionaries.
The first dictionary is empty. The second dictionary has integer
keys and string values. The third dictionary has mixed keys, with
one string key and one integer key. The fourth dictionary is
created using the dict() function, and
the fifth dictionary is created using the [(key, value)] syntax
Python

Dict
III SEM =
CSE{} 9
print("Empty Dictionary:
") print(Dict)
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer
PYTHON PROGRAMMING 20CS31P

III SEM CSE 10


PYTHON PROGRAMMING 20CS31P

print(Dict)
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair:
") print(Dict)
Output:
Empty

Dictionary:
{}
Dictionary with the use of Integer
Keys:
{1: 'Geeks', 2: 'For', 3:
'Geeks'} Dictionary with the use of
Mixed Keys:
{1: [1, 2, 3, 4], 'Name':
'Geeks'}
Dictionary with the use of
dict():
{1: 'Geeks', 2: 'For', 3:
'Geeks'} Dictionary with each item as
a pair:
{1: 'Geeks', 2: 'For'}
PYTHON OPERATOR:

Python Operators
Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

ExampleGet your own Python Server


print(10 + 5)

Run example »

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

III SEM CSE 11


PYTHON PROGRAMMING 20CS31P

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common
mathematical operations:

III SEM CSE 12


PYTHON PROGRAMMING 20CS31P

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators


Assignment operators are used to assign values to variables:

Operator Example Same As

III SEM CSE 13


PYTHON PROGRAMMING 20CS31P

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

III SEM CSE 14


PYTHON PROGRAMMING 20CS31P

<<= x <<= 3 x = x << 3

:= print(x := 3) x =
print(x)

ADVERTISEMENT

Python Comparison Operators


Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

III SEM CSE 15


PYTHON PROGRAMMING 20CS31P

<= Less than or equal to x <= y

Python Logical Operators


Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the not(x < 5 and x <
result is true

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but
if they are actually the same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the same x is y


object

III SEM CSE 16


PYTHON PROGRAMMING 20CS31P

is not Returns True if both variables are not the x is not y


same object

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified value is x in y


present in the object

not in Returns True if a sequence with the specified value is x not in y


not present in the object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Operator Name Description Exampl

& AND Sets each bit to 1 if both bits are 1 x&y

| OR Sets each bit to 1 if one of two bits is 1 x|y

III SEM CSE 17


PYTHON PROGRAMMING 20CS31P

^ XOR Sets each bit to 1 if only one of two bits is 1 x^y

~ NOT Inverts all the bits ~x

<< Zero fill left Shift left by pushing zeros in from the right and let x << 2
shift the leftmost bits fall off

>> Signed Shift right by pushing copies of the leftmost bit in


right shift from the left, and let the rightmost bits fall off

III SEM CSE 18


PYTHON PROGRAMMING 20CS31P

UNIT 3
CONTROL FLOW:
CONDITIONAL BLOCKS
In programming languages, most of the time in large projects we have to
control the flow of execution of our program and we want to execute some set
of statements only if the given condition is satisfied, and a different set of
statements when it’s not satisfied. Conditional statements are also known as
decision-making statements. We need to use these conditional statements to
execute the specific block of code if the given condition is true or false.
In Python we can achieve decision making by using the following statements:
• if statements

• if-else statements
• elif statements
• Nested if and if-else statements
• elif ladder
In this tutorial, we will discuss all the statements in detail with some real-time
examples
#1) if statements
Python if statement is one of the most commonly used conditional statements
in programming languages. It decides whether certain statements need to be
executed or not. It checks for a given condition, if the condition is true, then
the set of code present inside the ” if ” block will be executed otherwise not.
The if condition evaluates a Boolean expression and executes the block of code
only when the Boolean expression becomes TRUE.

Syntax:

If ( EXPRESSION == TRUE ):

III SEM CSE 19


PYTHON PROGRAMMING 20CS31P

Block of code
else:
Block of code
Here, the condition will be evaluated to a Boolean expression (true or false). If
the condition is true, then the statement or program present inside the ” if ”
block will be executed and if the condition is false, then the statements or
program present inside the “else” block will be executed.
Let’s see how it looks on a flow chart

III SEM CSE 20


PYTHON PROGRAMMING 20CS31P

If you observe the above flow-chart, first the controller will come to an if
condition and evaluate the condition if it is true, then the statements will be
executed, otherwise the code present outside the block will be executed.
Let’s see some examples of ” if ” statements.
Example:

1 num = 5

if (num < 10):

print(“Num is smaller than 10”)

print(“This statement will always be executed”)

Output: Num is smaller than 10.

This statement will always be executed.

III SEM CSE 21


PYTHON PROGRAMMING 20CS31P

In the above example, we declared a variable called ‘Num’ with the value as 5
and the ” if ” statement is checking whether the number is lesser than 10 or
not. If the condition is true then a set of statements inside the if block will be
executed.
Example: 2
a=7
b=0
if (a > b):
print(“a is greater than
b”) Output:
a is greater than b

In the above example, we are checking the relationship between a and b using
the greater than (>) operator in the if condition. If “a” is greater than “b” then
we will get the above output.
Example: 3
a=0
b=7i
f (b > a):
print(“b is greater than a”)

Output:
b is greater than a.

III SEM CSE 22


PYTHON PROGRAMMING 20CS31P

Example: 4
a=7
b=0
if (a):
print(“true”)
Output:
True

If you observe, in the above example, we are not using or evaluating any
condition in the “if” statement. Always remember that in any programming
language, the positive integer will be treated as true value and an integer
which is less than 0 or equal to 0 will be treated as false.
Here the value of a is 7 which is positive, hence it prints true in the
console output.
Example: 5
if (‘Python’ in [‘Java', ‘Python’, ‘C#’]):
print(“true”)
Output:
True

Here, we are verifying if the element ‘Python’ is present in the given list or not.
Hence it prints true because “ Python “ is present in the given list.
Let’s take one real-life example where we will use the Python if statement.

III SEM CSE 23


PYTHON PROGRAMMING 20CS31P

For Example: You have written an exam for a total score of 100 and if your
score is above or equal to 60 then you will be considered as PASS in the exam.
Let’s write the code for it.
Example: 6
passing_Score = 60
my_Score = 67
if(my_Score >= passing_Score):
print(“Congratulations! You have passed your exam”)
Output: Congratulations! You have passed your exam.

Remember to use the (:) operator at the end of the if statement, because
whatever the code you write after the colon operator will be a part of “if
block” and indentation is very important in Python.

Example: 7
passing_Score = 60
my_Score = 67 i
f(my_Score >= passing_Score):
print(“You passed the
exam”)
print(“Congratulations!”)
Output: You passed the exam Congratulations!

III SEM CSE 24


PYTHON PROGRAMMING 20CS31P

Here, print(“Congratulations!”) statement will always be executed even though


the given condition is true or false.
The problem with the above code is the statement ‘print(“Congratulations!”)’
will always be executed even if the condition is evaluated to true or false. But
in real-time, if you pass the exam or if you fail in the exam, then the system will
say Congratulations!!!.
In order to avoid this, Python provides one conditional statement called if-else.

III SEM CSE 25


PYTHON PROGRAMMING 20CS31P

UNIT 4
Control Flow:
Loops Python
Loops:
The flow of the programs written in any programming language is sequential
by default. Sometimes we may need to alter the flow of the program. The
execution of a specific code may need to be repeated several number of times.
For this purpose, the programming languages provide various types of loops
which are capable of repeating some specific code several numbers of times.
Consider the following diagram to understand the working of a loop statement.

Why we use loops in python?


• The looping simplifies the complex problems into the easy ones. It enables us
to alter the flow of the program so that instead of writing the same code again
and again,
• We can repeat the same code for a finite number of times.
• For example, if we need to print the first 10 natural numbers then, instead of
using the print statement 10 times, we can print inside a loop which runs up to
10 iterations.

Advantages of loopS:
There are the following advantages of loops in Python

III SEM CSE 26


PYTHON PROGRAMMING 20CS31P

1. It provides code re-usability.

III SEM CSE 27


PYTHON PROGRAMMING 20CS31P

2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or
linked lists).
Python While loop:
The Python while loop allows a part of the code to be executed until the given
condition returns false. It is also known as a pre-tested loop.
Syntax for while loop
while condition:
# body of while loop
A while loop evaluates the condition
If the condition evaluates to True, the code inside the while loop is executed.
condition is evaluated again.
This process continues until the condition is False.
When condition evaluates to False, the loop stops.

III SEM CSE 28


PYTHON PROGRAMMING 20CS31P

While loop Flowchart

Example-1: Program to print 1 to 10 using while loop


i=1
#The while loop will iterate until condition becomes false.
while(i<=10):
print(i)
i=i+1
Output:

Example -2: Program to print table of given numbers.


i=1
number = int(input("Enter the
number:")) while i<=10:

III SEM CSE 29


PYTHON PROGRAMMING 20CS31P

print("%d X %d = %d \n"%(number,i,number*i))
i = i+1
Output

Infinite while loop


If the condition is given in the while loop never becomes false, then the while
loop will never terminate, and it turns into the infinite while loop.
Any non-zero value in the while loop indicates an always-true condition,
whereas zero indicates the always-false condition. This type of approach is
useful if we want our program to run continuously in the loop without any
disturbance.
Example 1
while (1):
print("Hi! we are inside the infinite while loop")

Output:

Example-2
var = 1
while(var != 2):

III SEM CSE 30


PYTHON PROGRAMMING 20CS31P

i = int(input("Enter the number:"))

III SEM CSE 31


PYTHON PROGRAMMING 20CS31P

print("Entered value is %d"%(i))


Output:

Using else with while loop


Python allows us to use the else statement with the while loop also. The else
block is executed when the condition given in the while statement becomes
false. The else statement is optional to use with the while loop.
Example-1
i=1
while(i<=5):
print(i)
i=i+1
else:
print("The while loop exhausted")

Example-2 Program to print Fibonacci numbers to given limit

terms = int(input("Enter the terms


")) # first two intial terms
a=0
b=1
count = 0
if (terms <= 0):
print("Please enter a valid integer")

III SEM CSE 32


PYTHON PROGRAMMING 20CS31P

elif (terms == 1):


print("Fibonacci sequence upto",limit,":")
print(a)
else:
print("Fibonacci sequence:")
while (count < terms) :
print(a, end = ' ')
c=a+b
a=b
b=c
count += 1
Output:

Reversing a number using while loop in Python


n = int(input("Enter a number: "))
rev = 0
while n!=0:
r = n%10
rev = rev * 10 +
r n = n//10
print("Reversed number:”,rev)
Output

Finding the sum of even numbers using while loop


i=0
sum = 0
n = int(input("Enter the number n: "))

III SEM CSE 33


PYTHON PROGRAMMING 20CS31P

while i <= n:
if i % 2 == 0:
sum += i i += 1
print("Sum of even numbers till
n:",sum) Output:

Finding the factorial of a given number using while loop


n = int(input("Enter the number:
")) f =n
r=1
while f != 0 :
r *= f
f -= 1 p
rint("Factorial of”,n,"is:",r)
Output

III SEM CSE 34


PYTHON PROGRAMMING 20CS31P

UNIT 5
Data Collections
SETS
Set is an unordered data collection that is iterable, mutable and does not
contain any duplicate elements. Sets are used to store multiple values in a
single variable. The major advantage of set when compared to lists is that sets
are optimized for checking whether a specific element is present in the set. The
sets have this advantage because they are stored based on data structure
known as hash table.
Sets are represented by {} with the values enclosed in the curly braces.
Example:
fruits = {“apple”, “kiwi”, “orange”}
Concept of mutability:
Mutable refers to a feature where we have ability to change. In python
mutable is the ability of objects to change their values. Sets are mutable
meaning we change the values in the set. However, the elements in the set
should be immutable.
Features:
The following are the major features of sets.
 Sets are unordered: The elements in the set are not stored in the order as
specified in the definition of set.
 Set elements are unique: The duplicate elements in the set are represented
in the set only once.
 Sets are mutable: A set can be modified after its creation. The elements
contained in the set must be an immutable type.
 Sets are heterogeneous: sets can contain elements of different type.
Declaration and Initialization:

Sets can be created in 2 ways:

III SEM CSE 35


PYTHON PROGRAMMING 20CS31P

1. A set can be defined/declared using curly braces {} if you know the


elements when you are about to create them.
General syntax:
X = { , ,,…., }
Each is a distinct element in the set. These individual objects can
be any of the immutable data type.
Example:
subjects = {“python” , “DBMS” , “CN” , “CHMA” }
In the above example “subjects” is a set containing 4 elements
which are strings which denote different subjects studied in 3rd
semester CSE.
2. A set can be defined using built in set() function: we can use set()
function to declare/define sets .
General syntax:
X = set()
The argument to the set() function can be any iterable type or
simply any data collection type like lists, tuples, or strings.
Example:
sample_list =
[75,85,90,”Hello”] sample_set
= set(sample_list)
or we can create alternatively the same set sample_set as
sample_set = set([75,85,90,”Hello”]) which creates a set
by name sample_set.
Creating an empty set:
It is important to note that to create an empty set we need to use
only set() method . Nums = set() which will create an empty set.

If we try to create to empty set using the curly braces as shown


below.
Nums = {} . will create an empty dictionary .

III SEM CSE 36


PYTHON PROGRAMMING 20CS31P

Operations:
Below are the various operations which can be performed on the
sets. These can be accomplished with the built in methods
provided.
Adding an element to the set: add()
The add method can be used to add an element to the set. The
element can be any immutable data type. Below is the snapshot of
example code and its output when executed is highlighted in blue
color.

Update() : update method helps us in adding multiple elements to


the set . update method updates a set with the union of itself and
other elements supplied as arguments to the method. The
argument should be an iterable data type.
Below is the snapshot of example code and its output when
executed is highlighted in blue color.

III SEM CSE 37


PYTHON PROGRAMMING 20CS31P

Removing the elements from the set:


We have two methods in python to remove an element from the
set which are.
1. discard(): This method removes an element passed as argument
from the set if it is member of the set. Below is the snapshot of
example code and its output when executed is highlighted in blue
color.

2. remove(): This method removes an element passed as argument


from the set . The condition is the element must be the member
of the set. If the element is not present, then it will raise error.
Below is the snapshot of example code and its output when
executed is
highlighted in blue color.

Trying to delete an item which is not a member of the set through


remove() method will throw error. Below is the snapshot of
example code and its output when executed ishighlighted in blue
color and

III SEM CSE 38


PYTHON PROGRAMMING 20CS31P

error raised in red color.

III SEM CSE 39


PYTHON PROGRAMMING 20CS31P

Pop() : This method removes and returns an arbitrary set element


. This function raises error if the set is empty. Below is the
snapshot of example code and its output when executed is
highlighted in blue color.

Clear() : This method removes all the elements from this set.
Below is the snapshot of example code and its output when
executed is highlighted in blue color.

III SEM CSE 40


PYTHON PROGRAMMING 20CS31P

Other operations on sets:


Copy() : copy() method returns a shallow copy of a set.
Below is the snapshot of example code and its output when
executed is highlighted in blue color.

We can perform the classic operations on sets from mathematics


in python as well. Some of the most important ones are discussed
below. We can perform these either using methods or operators.
Union operation on python sets:
Union operation returns a set which contains all the elements of
the given two or more sets.
It can be performed by union() method or | operator in python. If
arts and science are two sets then Union of arts and science sets
will contain all the elements from both sets. Below is the snapshot
of example code and its output when executed is highlighted in
blue

III SEM CSE 41


PYTHON PROGRAMMING 20CS31P

UNIT 6
LISTS
Introduction
 In any programming language a variable can hold a single value
of any type at once.  To assign multiple values,we may need to
create separate variables and assign the values. But this method is
less efficient and more error prone.
 To overcome these demerits, Python provides data types to
store collection of data with a single name. These are lists, tuples,
sets and dictionaries.
Definition:
The list is a sequence data type which is used to store the
collection of data. Tuples and String are other types of sequence
data types.
A List can be defined as an ordered collection of data-items of any
data type and allows duplicated data items.
Lists are one of 4 built-in data types in Python used to store
collections of data, the other three are tuples, sets and dictionary,
all with different qualities and usage.
How to create list??
In Python a list can be created in three different ways
List can be created by placing comma sepearated values inside
square brackets.
syntax:
List_name=[item1,item2,.........itemn]
Where : List_name is any valid identifier
item1,item2,.......itemn can be value of any data type

Examples
1) List1=[1,2,3] # List of integers
III SEM CSE 42
PYTHON PROGRAMMING 20CS31P

2) List2=[1,2.3,”hello”,True] #Mixed type of


List
3) List3=[‘a’,’b’,’c’] # List of string

We can also create a empty list by using empty [ ] i.e,


List1=[] # creates empty list.
We can also create a list by using the list() constructor. Using this
constructor we can convert any data type to list.
Example: 1) Name=”KLMS”
print(Name) # Prints the name ‘KLMS’
# The string can be converted into list
List_Name=list(Name)
print(List_Name) # [‘K’,’L’,’M’,’S’]
2) TUPLE_EX=(1,True,45.5,"DCTE")
print("Tuple data items are",TUPLE_EX)
print("The data type belongs to",type(TUPLE_EX))
List_tuple=list(TUPLE_EX) print("The List data items
are:",List_tuple)
print("The data type belongs to",type(List_tuple))
Output

Basic operations on list:


1) Concatenation: + operator is used to concatenate one list with
other list
Examples:

III SEM CSE 43


PYTHON PROGRAMMING 20CS31P

1. a=['foo', 'bar', 'baz', 'qux', 'quux', 'corge']


print( a + ['ginger', 'garlic'])
# ['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'ginger', 'garlic'
2. b=[1,2,3]
c=[‘a’,’b’,’c’]
print(b+c)
# [1,2,3,’a’,’b’,’c’]
2) Repetition:* operator is used to generate the repeated sequence
or
replicate the sequences.
Example:
a=['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
print(a * 2)
#['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'foo', 'bar', 'baz','qux',
'quux', 'corge']
3) The in and not in membership operators can also be used with
the list to check whether a particular item is a member of list or
not.
Example:
a=['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
print( ‘foo’ in a)# prints True because ‘foo’ is present in a
print( ‘xyz’ in a) # prints False
print( ‘abc’ not in a) # Returns True as ‘abc’ is not present in a
print(‘foo’ not in a) # Returns False.

3) The comparison operators can also be used with the lists for
comparing one list with the other.
Example:
a = ['foo', 'bar', 'baz', 'qux']
print( ‘foo’ in a) # prints True because ‘foo’ is present in a
print( ‘xyz’ in a) # prints False
print( ‘abc’ not in a) # Returns True as ‘abc’ is not present in a

III SEM CSE 44


PYTHON PROGRAMMING 20CS31P

print(‘foo’ not in a) # Returns False


4) The comparison operators can also be used with the lists for
comparing one list with the other.
Example:
a = ['foo', 'bar', 'baz', 'qux']
b = ['baz', 'qux', 'bar', 'foo']
print( a == b) # Returns False.

How to access the data-items from the list??


 As an ordered sequence of elements, each item in a list can be
called individually, through indexing.
 The expression inside the bracket is called the index.
 Lists use square brackets [ ] to access individual items, with the
first item at index 0, the second item at index 1 and so on.
 The index provided within the square brackets indicates the
value being accessed. Each item in the list can be accessed by
indexing List_of_strings= ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']

Features of Lists:

III SEM CSE 45


PYTHON PROGRAMMING 20CS31P

1) Lists are ordered.


2) Lists can contain any arbitrary objects.
3) List elements can be accessed by index.
4) Lists can be nested to arbitrary depth.
5) Lists are dynamic. 6) Lists are mutable.
1) List item are ordered:
o The order in which you specify the elements when you define a
list is maintained for that list’s lifetime.
o a = ['foo', 'bar', 'baz', 'qux']
b = ['baz', 'qux', 'bar', 'foo']
# The above defined lists have the same items but their order is
different. Therefore the lists a and b are different.

2) Lists can contain any arbitrary objects: A list can contain data
items of any type
3) List items can be accessed by index: Each individual data items
from the list can be accessed by indexing. The index for a data
item in the list can be positive or negative.
4) Lists can be nested to arbitrary depth.
 The items in the list can be of any type.
 A list can contain another list as its item.
 A list can contain sublists, which in turn can contain sublists
themselves, and so on to arbitrary depth.
 Example:
x = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']
print(x) ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']
print(x)

III SEM CSE 46


PYTHON PROGRAMMING 20CS31P

 The following figure shows the object structure of list x which


contains nested lists as its data items.

III SEM CSE 47


PYTHON PROGRAMMING 20CS31P

UNIT 7
DICTIONARY
Dictionary

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow


duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values:

Declaration and Initialization:

You can initialize a dictionary with multiple items at once. Here's how:

my_dictionary = {
'apple': 'A sweet, edible fruit',
'banana': 'A long, curved fruit',
'cherry': 'A small, round fruit',
}

In this example, we've initialized a dictionary with three key-value pairs.


Each pair is separated by a comma, and the key and value within each pair
are separated by a colon.

Accessing Dictionary Values

Now that we have a dictionary with some items, let's learn how to access
these items. We can do this using the keys:

my_dictionary = {
'apple': 'A sweet, edible fruit',
'banana': 'A long, curved fruit',
'cherry': 'A small, round fruit',
}

print(my_dictionary['apple']) # Prints: A sweet, edible fruit

III SEM CSE 48


PYTHON PROGRAMMING 20CS31P

In this example, we've accessed the value of 'apple' using the key and
printed it. It's like saying, "Give me the definition of 'apple'."

Basic operations:

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert
specified value

III SEM CSE 49


PYTHON PROGRAMMING 20CS31P

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

Membership operators:

The Python membership operators test for the membership of an


object in a sequence, such as strings, lists, or tuples. Python
offers two membership operators to check or validate the
membership of a value. They are as
follows:
Membership
Operator Description Syntax

Returns True if the value


in Operator value in sequence
exists in a sequence, else
returns False

Returns False if the value value not


not in Operator
exists in a sequence, else in
returns True sequence

Indexing:

The concept of dictionary is similar to that of map data


structure in C++ language, but with the exception that keys in
dictionary has nothing to do with its ordering, i.e it is not sorted
unlike C++ in which the keys are sorted internally. This opens
up the problem in which we might have to find the exact
position of key in the dictionary. Let’s discuss certain ways in
which this task can be performed.
Method #1 : Using list comprehension + enumerate() The
combination of above functions together can perform this
particular task. In this, first the dictionary is converted to a pair
III SEM CSE 50
PYTHON PROGRAMMING 20CS31P

UNIT 8
Arrays and
Strings Arrays
Features:
 Each array element is of the same data type and size. For
example: For an array of integers with the int data type,
each element of the array will occupy 4 bytes.
 Elements of the array are stored in contiguous memory
locations.
Create:
Array in Python can be created by importing an
array module. array(data_type, value_list) is used to create array in
Python with data type and value list specified in its arguments.
In below code Python create array : one of integers and one of
doubles. It then prints the contents of each array to the

import array as arr


a = arr.array('i', [1, 2, 3])
print("The new created array is : ", end=" ")
for i in range(0, 3):
print(a[i], end="
")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("\nThe new created array is : ",
end=" ") for i in range(0, 3):
print(b[i], end=" ")

Output
The new created array is1
2 3

The new created array is : 1


2 3

The new created array is : 2.5 3.2


3.3

Initialize:

III SEM CSE 51


PYTHON PROGRAMMING 20CS31P

In Python, it’s common to encounter scenarios where you need


to store lists in a dictionary. Often, this involves checking if a
key exists and then creating a list for that key. However, a
more efficient approach is to initialize the dictionary keys with
empty lists from the start. Let’s explore some methods to
accomplish this.
How to Initialize a Dictionary with an Empty List
It is a good practice to initialize a dictionary with empty lists in
Python. This helps in working with dynamic data structures. This
also helps in appending items to a list associated with a key.
Initializing an empty list while creating a dictionary also eases the
process of later creating a list while checking for key
availability.
We will learn various methods to initialize an empty list
dictionary. Initialize a Dictionary of Empty Lists using
Dictionary Comprehension Dictionary comprehension is the
most sought method to do
this initialization. In this method, we create the no. of
keys we require and then initialize the empty list as we keep
on creating the keys, to facilitate the
append operation afterward without an error.
 Python3
# Python3 code to demonstrate

# to initialize dictionary with

list # using dictionary

comprehension

# using dictionary comprehension to construct

new_dict = {new_list: [] for new_list in

range(4)}

# printing result

print ("New dictionary with empty lists as keys : " + str(new_dict))

III SEM CSE 52


PYTHON PROGRAMMING 20CS31P

Output
New dictionary with empty lists as keys : {0: [], 1: [], 2:
[], 3: []}New dictionary with empty lists as keys : {0: [],
1: [], 2: [], 3: []}

Strings:

III SEM CSE 53


PYTHON PROGRAMMING 20CS31P

In Python, a string is any text enclosed in double or single


quote marks in Python, including alphabets, special
characters, and numerals. In all programming languages,
this data type is the most prevalent.

Syntax
Following is the syntax of Python dictionary str() method −

str(dict)

Constructing python function is a constructor that is used to create


dictionaries. Dictionary is a data structure in Python that
contains elements in the form of a value and its respective
key. It is a collection of data that is unordered, indexed,
and can be changed after the definition of the dictionary.

Example 1: Create Dictionary Using Keyword Arguments Only

num = dict (x = 10, y =

15) print (“numbers = “,

num) print (type (num))

empty = dict ()

print (“empty =”,

empty) print (type

(empty))
Assigning:
Add to Python Dictionary Without Overwriting Values

Using the = assignment operator overwrites the values of existing keys


with the new values. If you know that your program might have
duplicate keys, but you don't want to overwrite the original
values, then you can
conditionally add values using an if statement.

dict_example = {'a': 1, 'b': 2}

III SEM CSE 54


PYTHON PROGRAMMING 20CS31P

print("original dictionary: ", dict_example)

dict_example['a'] = 100 # existing key, overwrite


dict_example['c'] = 3 # new key, add
dict_example['d'] = 4 # new key, add

print("updated dictionary: ", dict_example)

Output
original dictionary: {'a': 1, 'b': 2}
updated dictionary: {'a': 100, 'b': 2, 'c': 3, 'd': 4}

Indexing :
In Python, indexing refers to the process of accessing a specific
element in a sequence, such as a string or list, using its position
or index number. Indexing in Python starts at 0, which means
that the first element in a sequence has an index of 0, the
second element has an index of 1, and so on. For example, if
we have a string "Hello", we can access the first letter "H" using
its index 0 by using the square bracket notation: string[0].
Python's built-in index() function is a useful tool for finding the index of a
specific element in a sequence. This function takes an argument
representing the value to search for and returns the index of the first
occurrence of that value in the sequence.
If the value is not found in the sequence, the function raises a ValueError.
For example, if we have a list [1, 2, 3, 4, 5], we can find the index of the
value 3 by calling list.index(3), which will return the value 2 (since 3 is the
third element in the list, and indexing starts at 0).
The index() function is a powerful tool in Python as it simplifies the process
of finding the index of an element in a sequence, eliminating the need for
writing loops or conditional statements. This function is especially useful
when working with large datasets or complex structures, where manual
searching could be time-consuming and error-prone.

Python Index Examples


The method index() returns the lowest index in the list where the element
searched for appears. If any element which is not present is searched, it
returns a Value Error.

III SEM CSE 55


PYTHON PROGRAMMING 20CS31P

Example
Get your own Python
Server
What is the position of the value "cherry":

fruits = ['apple', 'banana', 'cherry']

x = fruits.index("cherry”)

String operators:

III SEM CSE 56


PYTHON PROGRAMMING 20CS31P

UNIT 9
FUNCTIONS
Introduction:
Python Functions is a block of statements that return the specific
task. The idea is to put some commonly or repeatedly done tasks
together and make a function so that instead of writing the
same code again and again for different inputs, we can do the
function calls to reuse code contained in it over and over
again.

Some Benefits of Using Functions


 Increase Code Readability
 Increase Code Reusability

Python Function Declaration


The syntax to declare a function is:

Need of Function:
So it turns out you already know what a function is. You have
been using it the whole time while studying this tutorial!

For example, main() is a function, which is used to execute


code, and printf() is a function; used to output/print text to
the screen:

III SEM CSE 57


PYTHON PROGRAMMING 20CS31P

Example
int main() {
printf("Hello World!");
return 0;
}
Types:
There are two types of functions in python:

 User-Defined Functions - these types of functions are defined by the


user to perform any specific task
 Built-in Functions - These are pre-defined functions in python.

III SEM CSE 58


PYTHON PROGRAMMING 20CS31P

Define function:

Python def keyword is used to define a function, it is placed


before a function name that is provided by the user to create a
user-defined function. In Python, a function is a logical unit of
code containing a sequence of statements indented under a
name given using the “def” keyword. In Python def keyword is
the most used keyword.

Calling Function:
To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

Arguments:
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:

III SEM CSE 59


PYTHON PROGRAMMING 20CS31P

Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias
")
my_function("Linus"
)

Recursion:
Recursion is a common mathematical and programming concept. It means
that a function calls itself. This has the benefit of meaning that you can loop
through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.

Example
Recursion Example

def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-
1)
else: print(resul
t)
return
result result = 0

print("\n\nRecursion Example
Results") tri_recursion(6)

III SEM CSE 60


PYTHON PROGRAMMING 20CS31P

UNIT 10
MODULES AND PACKAGES
Why Modules:
Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module
To create a module just save the code you want in a file with the file
extension .py:

Example
Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement:

Example
Import the module named mymodule, and call the greeting function:

import mymodule

my module.greeting("Jonathan")

Variables in Module
The module can contain functions, as already described, but also variables of
all types (arrays, dictionaries, objects etc):

Example
Save this code in the file mymodule.py

III SEM CSE 61


PYTHON PROGRAMMING 20CS31P

person1 =
{ "name": "John",
"age": 36,
"country":
"Norway"
}

Example
Import the module named mymodule, and access the person1 dictionary:

import mymodule

a =
mymodule.person1["age"] print(a)

Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Example
Create an alias for mymodule called mx:

import mymodule as mx

a =
mx.person1["age"] print(a)

Built-in Modules
There are several built-in modules in Python, which you can import whenever
you like.

Example
Import and use the platform module:

III SEM CSE 62


PYTHON PROGRAMMING 20CS31P

import platform

x =
platform.system() print(x)

Packages:

Python Package

A package is a container that contains various functions to


perform specific tasks. For example, the math
sqrt()package

includes the

function to perform the square root of a number.


While working on big projects, we have to deal with a large
amount of code, and writing everything together in the same file
will make our code look messy. Instead, we can separate our code
into multiple files by keeping the related code together in
packages.

Now, we can use the package whenever we need it in our


projects. This way we can also reuse our code.

III SEM CSE 63


PYTHON PROGRAMMING 20CS31P

Package Model Structure in Python


Programming
Suppose we are developing a game. One possible organization of
packages and modules could be as shown in the figure below.

Importing module from a package


In Python, we can import modules from packages using the dot (.)

For example, if we want to start module in the above


import the example, it
can be done as follows:
import Game.Level.start

III SEM CSE 64


PYTHON PROGRAMMING 20CS31P

UNIT 11
NUMPY AND PANDAS
Numpy:
NumPy is a Python library used for working with arrays.

It also has functions for working in domain of linear algebra, fourier


transform, and matrices.

NumPy was created in 2005 by Travis Oliphant. It is an open source project


and you can use it freely.

NumPy stands for Numerical Python.

The need of Numpy:


In Python we have lists that serve the purpose of arrays, but they are slow to
process.

NumPy aims to provide an array object that is up to 50x faster than


traditional Python lists.

The array object in NumPy is called ndarray, it provides a lot of supporting


functions that make working with ndarray very easy.

Arrays are very frequently used in data science, where speed and resources
are very important.

Numpy Environment setup:


NumPy doesn't come bundled with Python. We have to install it using
the python pip installer. Execute the following command.

1. $ pip install numpy

It is best practice to install NumPy with the full SciPy stack. The binary
distribution of the SciPy stack is specific to the operating systems.

Windows
On the Windows operating system, The SciPy stack is provided by the
Anaconda which is a free distribution of the Python SciPy package.

III SEM CSE 65


PYTHON PROGRAMMING 20CS31P

It can be downloaded from the official website:


https://www.anaconda.com/. It is also available for Linux and Mac.

Numpy arithmetic function:

Simple Arithmetic
You could use arithmetic operators + - * / directly between NumPy arrays,
but this section discusses an extension of the same where we have functions
that can take any array-like objects e.g. lists, tuples etc. and perform
arithmetic conditionally.

Addition
The add() function sums the content of two arrays, and return the results in
a new array.

Example
Add the values in arr1 to the values in arr2:

import numpy as np

arr1 = np.array([10, 11, 12, 13, 14, 15])


arr2 = np.array([20, 21, 22, 23, 24, 25])

newarr = np.add(arr1,

arr2) print(newarr)

Subtraction
The subtract() function subtracts the values from one array with the
values from another array, and return the results in a new array.

Example
Subtract the values in arr2 from the values in arr1:

import numpy as np

arr1 = np.array([10, 20, 30, 40, 50, 60])


arr2 = np.array([20, 21, 22, 23, 24, 25])

III SEM CSE 66


PYTHON PROGRAMMING 20CS31P

newarr = np.subtract(arr1,

arr2) print(newarr)

Multiplication
The multiply() function multiplies the values from one array with the
values from another array, and return the results in a new array.

Example
Multiply the values in arr1 with the values in arr2:

import numpy as np

arr1 = np.array([10, 20, 30, 40, 50, 60])


arr2 = np.array([20, 21, 22, 23, 24, 25])

newarr = np.multiply(arr1,

arr2) print(newarr)

Division
The divide() function divides the values from one array with the values
from another array, and return the results in a new array.

Example
Divide the values in arr1 with the values in arr2:

import numpy as np

arr1 = np.array([10, 20, 30, 40, 50, 60])


arr2 = np.array([3, 5, 10, 8, 2,

33]) newarr = np.divide(arr1,

arr2) print(newarr)

Power

III SEM CSE 67


PYTHON PROGRAMMING 20CS31P

The power() function rises the values from the first array to the power of
the values of the second array, and return the results in a new array.

Example
Raise the valules in arr1 to the power of values in arr2:

import numpy as np

arr1 = np.array([10, 20, 30, 40, 50, 60])


arr2 = np.array([3, 5, 6, 8, 2, 33])

newarr = np.power(arr1,

arr2) print(newarr)

Remainder
Both the mod() and the remainder() functions return the remainder of the
values in the first array corresponding to the values in the second array, and
return the results in a new array.

Example
Return the remainders:

import numpy as np

arr1 = np.array([10, 20, 30, 40, 50, 60])


arr2 = np.array([3, 7, 9, 8, 2, 33])

newarr = np.mod(arr1,

arr2) print(newarr)

Quotient and Mod


The divmod() function return both the quotient and the the mod. The return
value is two arrays, the first array contains the quotient and second array
contains the mod.

Example
Return the quotient and mod:

III SEM CSE 68


PYTHON PROGRAMMING 20CS31P

import numpy as np

arr1 = np.array([10, 20, 30, 40, 50, 60])


arr2 = np.array([3, 7, 9, 8, 2, 33])

newarr = np.divmod(arr1,

arr2) print(newarr)

PANDAS INTRODUCTION:

What is Pandas ?
Pandas is a Python library used for working with data sets.

It has functions for analyzing, cleaning, exploring, and manipulating data.

The name "Pandas" has a reference to both "Panel Data", and "Python Data
Analysis" and was created by Wes McKinney in 2008.

Why Use Pandas ?


Pandas allows us to analyze big data and make conclusions based on
statistical theories.

Pandas can clean messy data sets, and make them readable and relevant.

Relevant data is very important in data science.

Environment Setup:

Standard Python distribution doesn't come bundled with Pandas module. A


lightweight alternative is to install NumPy using popular Python package
installer, pip.

pip install pandas

If you install Anaconda Python package, Pandas will be installed by default


with the following –

Windows
 Anaconda (from https://www.continuum.io) is a free Python distribution
for SciPy stack. It is also available for Linux and Mac.

III SEM CSE 69


PYTHON PROGRAMMING 20CS31P

 Canopy (https://www.enthought.com/products/canopy/) is available as


free as well as commercial distribution with full SciPy stack for
Windows, Linux and Mac.
 Python (x,y) is a free Python distribution with SciPy stack and Spyder
IDE for Windows OS. (Downloadable from http://python-xy.github.io/)

Windows
 Anaconda (from https://www.continuum.io) is a free Python distribution
for SciPy stack. It is also available for Linux and Mac.
 Canopy (https://www.enthought.com/products/canopy/) is available as
free as well as commercial distribution with full SciPy stack for
Windows, Linux and Mac.
 Python (x,y) is a free Python distribution with SciPy stack and Spyder
IDE for Windows OS. (Downloadable from http://python-xy.github.io/)

Linux
Package managers of respective Linux distributions are used to
install one or more packages in SciPy stack.

For Ubuntu Users

sudo apt-get install python-numpy python-scipy python-


matplotlibipythonipythonnotebook
python-pandas python-sympy python-nose

For Fedora Users

sudo yum install numpyscipy python-matplotlibipython python-pandas


sympy
python-nose atlas-devel

III SEM CSE 70


PYTHON PROGRAMMING 20CS31P

UNIT 12
FILE CONCEPT
Features:
File handling in Python is a powerful and versatile tool that can
be used to perform a wide range of operations. However, it is
important to carefully consider the advantages and
disadvantages of file handling when writing Python programs,
to ensure that the code is secure, reliable, and performs well.
In this article we will explore Python File Handling, Advantages,
Disadvantages and How open, write and append functions works in
python file.

File operations:
File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not
exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Opening files:
Open a File on the Server

Assume we have the following file, located in the same folder as Python:

III SEM CSE 71


PYTHON PROGRAMMING 20CS31P

demofile.txt

Hello! Welcome to demofile.txt


This file is for testing
purposes. Good Luck!

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for
reading the content of the file:

Example

f = open("demofile.txt", "r")
print(f.read())

Closing Files:

The close() method closes an open file.

You should always close your files, in some cases, due to buffering, changes
made to a file may not show until you close the file.

Syntax
file.close()

Writing to files:

To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example
Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more
content!") f.close()

#open and read the file after the appending:

III SEM CSE 72


PYTHON PROGRAMMING 20CS31P

f = open("demofile2.txt", "r")
print(f.read())

Reading files:
Read Only (‘r’) : Open text file for reading. The handle is positioned
at the beginning of the file. If the file does not exist, raises the
I/O error. This is also the default mode in which a file is
opened.
Read and Write (‘r+’): Open the file for reading and writing. The
handle is positioned at the beginning of the file. Raises I/O error

File Methods:
Python has a set of methods available for the file object.

III SEM CSE 73


PYTHON PROGRAMMING 20CS31P

UNIT 13
ERROR AND EXCEPTION HANDLING
Errors are the problems in a program due to which the program
will stop the execution. On the other hand, exceptions are raised
when some internal events occur which changes the normal flow
of the program. Two types of Error occurs
in python.
1. Syntax errors
2. Logical errors (Exceptions)

Python Errors:
Syntax Errors
Syntax errors, also known as parsing errors, are perhaps the most
common kind of complaint you get while you are still learning Python:

while True print('Hello world')


File "<stdin>", line 1
while True print('Hello world')
^^^^^
SyntaxError: invalid
syntax

The parser repeats the offending line and displays little ‘arrow’s pointing at the
token in the line where the error was detected. The error may be caused by
the absence of a token before the indicated token. In the example, the
error is detected at the
, since a
function print() colon ( ':') is missing before it. File name and line number are
printed so you know where to look in case the input came from a script.

Exceptions
Even if a statement or expression is syntactically correct, it may cause an
error when an attempt is made to execute it. Errors detected
during execution are called exceptions and are not unconditionally
fatal: you will soon learn how to handle them in Python programs. Most
exceptions are not handled by programs, however, and result in error
messages as shown here:

III SEM CSE 74


PYTHON PROGRAMMING 20CS31P

10 * (1/0)
Traceback (most recent call
last): File "<stdin>", line 1,
in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call
last): File "<stdin>", line 1,
in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call
last): File "<stdin>", line 1,
The last line of the error message indicates what happened. Exceptions
come in different types, and the type is printed as part of the message:
the types in the example are ZeroDivisionError, NameError and
TypeError. The string printed as the exception type is the name of the
built-in exception that occurred. This is true for all built-in exceptions, but
need not be true for user-defined exceptions (although it is a useful
convention). Standard exception names are built-in identifiers (not
reserved keywords).

The rest of the line provides detail based on the type of exception and
what caused it.

The preceding part of the error message shows the context where the
exception occurred, in the form of a stack traceback. In general it contains
a stack traceback listing source lines; however, it will not display lines
read from standard input.
How to Catch Exceptions:
Different types of exceptions in python:
In Python, there are several built-in Python exceptions that can be
raised when an error occurs during the execution of a program.
Here are some of the most common types of exceptions in
Python:
 SyntaxError: This exception is raised when the interpreter
encounters a syntax error in the code, such as a
misspelled keyword, a missing colon, or an unbalanced
parenthesis.
 TypeError: This exception is raised when an operation
or function is applied to an object of the wrong type,
such as adding a string to an integer.

III SEM CSE 75


PYTHON PROGRAMMING 20CS31P

 IndexError: This exception is raised when an index is out


of range for a list, tuple, or other sequence types.
 KeyError: This exception is raised when a key is not
found in a dictionary.

Raising Exceptions:
As a Python developer you can choose to throw an exception if a condition
occurs.

To throw (or raise) an exception, use the raise keyword.

ExampleGet your own Python Server


Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example
Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

III SEM CSE 76


PYTHON PROGRAMMING 20CS31P

III SEM CSE 77

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy