Python Programming Chapter 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

Python Programming Chapter 3

 Python String

 In Python, Strings are arrays of bytes representing Unicode characters.


 However, Python does not have a character data type, a single character is
simply a string with a length of 1.
 Square brackets can be used to access elements of the string.

Creating a String
Strings in Python can be created using single quotes or double quotes or even
triple quotes.
CODE;-
# Python Program for
# Creation of String
#
# Creating a String
# with single Quotes
String1 = 'Welcome to the Latur'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a AB"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String
# with triple Quotes
String1 = '''I'm a AB and I live on "Earth"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple


# Quotes allows multiple lines
String1 = '''
Hello
Cocsit
Latur'''
print("\nCreating a multiline String: ")
print(String1)

By R.S. Jadhav Page 1


Python Programming Chapter 3

OUTPUT:-

String with the use of Single Quotes:

Welcome to the Latur

String with the use of Double Quotes:

I'm a AB

String with the use of Triple Quotes:

I'm a AB and I live on "Earth"

Creating a multiline String:

Hello

Cocsit

Latur

Accessing characters in Python

 In Python, individual characters of a String can be accessed by using the


method of Indexing.
 Indexing allows negative address references to access characters from
the back of the String, e.g. -1 refers to the last character, -2 refers to the
second last character, and so on.

By R.S. Jadhav Page 2


Python Programming Chapter 3

CODE:-

# Python Program to Access


# characters of String

String1 = "HELLOCOCSITLATUR"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

OUTPUT:-
Initial String:
HELLOCOCSITLATUR

First character of String is:


H

Last character of String is:


R

String Slicing

 To access a range of characters in the String, the method of slicing is


used. Slicing in a String is done by using a Slicing operator (colon).

CODE:-

# Python Program to
# demonstrate String slicing

# Creating a String
By R.S. Jadhav Page 3
Python Programming Chapter 3

String1 = "HELLOCOCSITLATUR"
print("Initial String: ")
print(String1)
#Printing start index value
print("Start Index:")
print(String1[5:])
#Printing End index value
print("End Index:")
print(String1[:9])
# Printing 3rd to 12th character
print("\nSlicing characters from 3-12: ")
print(String1[3:12])

# Printing characters between


# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])

OUTPUT:-

Initial String:

HELLOCOCSITLATUR

Start Index:

COCSITLATUR

End Index:

HELLOCOCS

Slicing characters from 3-12:

LOCOCSITL

Slicing characters between 3rd and 2nd last character:

LOCOCSITLAT

By R.S. Jadhav Page 4


Python Programming Chapter 3

String Formatting in Python


String formatting is the process of infusing things in the string dynamically and
presenting the string. There are four different ways to perform string
formatting:-
 Formatting with % Operator.
 Formatting with format() string method.
 Formatting with string literals, called f-strings.
 Formatting with String Template Class

Formatting string using % Operator


It is the oldest method of string formatting. Here we use the modulo %
operator. The modulo % is also known as the “string-formatting operator”.

CODE:-

# Python program to demonstrate the use of formatting


using %

# Initialize variable as a string


variable = '15'
string = "Variable as string = %s" %(variable)
print (string )

# Printing as raw data


print ("Variable as raw data = %r" %(variable))

# Convert the variable to integer


# And perform check other formatting options

variable = int(variable) # Without this the below


statement
# will give error.
string = "Variable as integer = %d" %(variable)
print (string)
print ("Variable as float = %f" %(variable))

By R.S. Jadhav Page 5


Python Programming Chapter 3

# printing as any string or char after a mark


print ("Variable as printing with special char = %chello"
%(variable))

print ("Variable as hexadecimal = %x" %(variable))


print ("Variable as octal = %o" %(variable))
print("Hello %s"%('World!'))
print("Value of A: %d"%10)

OUTPUT:-

Variable as string = 15

Variable as raw data = '15'

Variable as integer = 15

Variable as float = 15.000000

Variable as printing with special char = ☼hello

Variable as hexadecimal = f

Variable as octal = 17

Hello World!

Value of A: 10

Float precision with the placeholder method:

 Floating-point numbers use the format %a.bf.


 Here, a would be the minimum number of digits to be present in the
string; these might be padded with white space if the whole number
doesn’t have this many digits.
 Close to this, bf represents how many digits are to be displayed after the
decimal point.
Let us see a few examples:
Float point precision using % operator:-

CODE:-

By R.S. Jadhav Page 6


Python Programming Chapter 3

print('The value of float point is: %5.4f' %(30.58967))


print('The value of float point is: %6.3f' %(30.58967))

OUTPUT:-

The value of float point is: 30.5897

The value of float point is: 30.590

You can use multiple format conversion types in a single print statement

CODE:-

variable = 20

string = "Variable as integer = %d \n\


Variable as float = %f" %(variable, variable)

print (string)

OUTPUT:-
Variable as integer = 20
Variable as float = 20.000000

Formatting string using format() method:-


 Format() method was introduced with Python3 for handling complex
string formatting more efficiently.
 Formatters work by putting in one or more replacement fields and
placeholders defined by a pair of curly braces { } into a string and
calling the str.format().
 The value we wish to put into the placeholders and concatenate with the
string passed as parameters into the format function.

Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)

Formatting string using format() method

By R.S. Jadhav Page 7


Python Programming Chapter 3

The .format() method has many advantages over the placeholder method:
 We can insert object by using index-based position

 We can insert objects by using assigned keywords

 We can reuse the inserted objects to avoid duplication

CODE:-
print('We all are {}.'.format('equal'))
print('{2} {1} {0}'.format('directions',
'the', 'Read'))
print('a: {a}, b: {b}, c: {c}'.format(a = 1,
b = 'Two',
c = 12.3))
print('We {p} {p} {p}'.format(p = 'are'))

OUTPUT:-

We all are equal.

Read the directions

a: 1, b: Two, c: 12.3

We are are are

Float precision with the .format() method:

Syntax: {[index]:[width][.precision][type]}

CODE:-

a = 30.58967
print("Float Point Number: {0:6.4f}".format(a))
print("Float Point Number: {0:5.3f}".format(a))
print("Float Point Number: {0:4.2f}".format(a))

OUTPUT:-

Float Point Number: 30.5897

Float Point Number: 30.590

By R.S. Jadhav Page 8


Python Programming Chapter 3

Float Point Number: 30.59

Formatted String using F-strings

 To create an f-string, prefix the string with the letter “ f ”.


 The string itself can be formatted in much the same way that you would
with str.format().
 F-strings provide a concise and convenient way to embed python
expressions inside string literals for formatting.
 This new formatting syntax is very powerful and easy.
 You can also insert arbitrary Python expressions and you can even do
arithmetic operations in it.
CODE:-

a = 'A'
print(f"We are all {a}")
b = 10
c = 20
print(f"Addition is: {b+c}")

d = 30
print(f"This is the value of d: {d}")

e = 30.58967
print(f"This is float point number: {e:{1}.{6}}")
print(f"This is float point number: {e:{2}.{5}}")
print(f"This is float point number: {e:{3}.{4}}")

OUTPUT:-
We are all A
Addition is: 30
This is the value of d: 30
This is float point number: 30.5897
This is float point number: 30.59
This is float point number: 30.59

By R.S. Jadhav Page 9


Python Programming Chapter 3

 Modifying String:-
Python strings are immutable

Python recognize as strings everything that is delimited by quotation marks


(” ” or ‘ ‘).

CODE:-

a = "Your_Name_is_displayed_on_TV."
print(a)
print(len(a)) # length of string
# Modifying string
print(a.upper()) # upper the letters
print(a.lower()) # lower the letters
print(a.capitalize()) # capital the first letter of total
string
print(a.title()) # capital the first letter of word in
total string
print(a.swapcase()) # capital to small and small to
capital
print(a.count('o')) #count 'o' in string
print(a.count('_')) # count '_' in string
print(a.find('Name')) #find the position in string
print(a.find('T')) #find particular one value in string
print(a.index('on')) # find the letters on in string
print(a.split('is')) # split from 'is' word
print(a.split('dis')) #split from 'dis' word
print(a.startswith('Y')) # If string starts with 'Y' then
print true,otherwise returns false.
print(a.endswith('.'))# If string ends with '.' then print
true,otherwise returns false.
print('.'*30) # repeating of string
a.replace('Your','Our')
print(a) # replacing the word from existing word
print(" ".join(a)) #add a whitespace between every char
print("+".join(a)) #add + whitespace between every char

# String Cocatenation
b = 'ABC'

By R.S. Jadhav Page 10


Python Programming Chapter 3

c = 'DEF'
print(b+c)

OUTPUT:-

Your_Name_is_displayed_on_TV.

29

YOUR_NAME_IS_DISPLAYED_ON_TV.

your_name_is_displayed_on_tv.

Your_name_is_displayed_on_tv.

Your_Name_Is_Displayed_On_Tv.

yOUR_nAME_IS_DISPLAYED_ON_tv.

26

23

['Your_Name_', '_d', 'played_on_TV.']

['Your_Name_is_', 'played_on_TV.']

True

True

..............................

Your_Name_is_displayed_on_TV.

Your_Name_is_displayed_on_TV.

Y+o+u+r+_+N+a+m+e+_+i+s+_+d+i+s+p+l+a+y+e+d+_+o+n+_+T+V+.

By R.S. Jadhav Page 11


Python Programming Chapter 3

ABCDEF

By R.S. Jadhav Page 12


Python Programming Chapter 3

 FILE HANDLING

 Python too supports file handling and allows users to handle files i.e., to
read and write files, along with many other file handling options, to
operate on files.

 The concept of file handling has stretched over various other languages,
but the implementation is either complicated or lengthy, but like other
concepts of Python, this concept here is also easy and short.

 Python treats file differently as text or binary and this is important. Each
line of code includes a sequence of characters and they form text file.
Each line of a file is terminated with a special character, called the EOL
or End of Line characters like comma {,} or newline character.

 It ends the current line and tells the interpreter a new one has begun.
Let’s start with Reading and Writing files.

Working of open() function


Before performing any operation on the file like read or write, first we have to
open that file. For this, we should use Python’s inbuilt function open()
Syntax: variable = open(‘filename’, ‘mode’)

Where the following mode is supported:


1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains
some data then it will be overridden.
3. a: open an existing file for append operation. It won’t override existing
data.
4. r+: To read and write data into the file. The previous data in the file will
not be deleted.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.

CODE:-
a = open('file.txt','r')
for i in a:
print(i)

By R.S. Jadhav Page 13


Python Programming Chapter 3

OUTPUT:-
Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

The open command will open the file in the read mode and the for loop will
print each line present in the file.

Working of read() mode


There is more than one way to read a file in Python. If you need to extract a
string that contains all characters in the file then we can use file.read(). The
full code would work like this:

CODE:-
a = open('file.txt','r')
print(a.read())

OUTPUT:-

Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
By R.S. Jadhav Page 14
Python Programming Chapter 3

Hello_World!
Hello_World!
Hello_World!
Hello_World!

Another way to read a file is to call a certain number of characters like in the
following code the interpreter will read the first five characters of stored data
and return it as a string:

CODE:-

a = open('file.txt','r')
print(a.read(1))
print(a.read(2))
print(a.read(3))
print(a.read(4))

OUTPUT:-

el

By R.S. Jadhav Page 15


Python Programming Chapter 3

lo_

Worl

Creating a file using write() mode


 Let’s see how to create a file and how write mode works:
To manipulate the file, write the following in your Python environment:
 The close() command terminates all the resources in use and frees the
system of this particular program.

CODE;-

a = open('file.txt','w')
a.write("This is write function")
a.write('''This will override
data which is
stored in our file''')
a.close()

OUTPUT:-

By R.S. Jadhav Page 16


Python Programming Chapter 3

Working of append() mode


Let’s see how the append mode works:

CODE:-

a = open('file.txt','a')
a.write("\nThis is APPEND MODE")
a.write('''This will NOT override
data which is
stored in our file''')
a.close()

OUTPUT:-

Using read along with the with() function


We can also use the read function along with the with() function:
CODE:-
By R.S. Jadhav Page 17
Python Programming Chapter 3

with open('file.txt','r') as a:
for i in a:
print(i)

OUTPUT:-

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

Hello_World!

CODE:-
with open('file.txt','r') as a:
print(a.read())

OUTPUT:-
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!
Hello_World!

By R.S. Jadhav Page 18


Python Programming Chapter 3

Using write along with the with() function


We can also use the write function along with the with() function:

CODE:-
with open('file.txt','w') as a:
a.write("This is a write function")
a.write('''
This will override
existing data
''')

OUTPUT:-

split() using file handling


We can also split lines using file handling in Python. This splits the variable
when space is encountered. You can also split using any characters as we
wish. Here is the code:
CODE:-
with open("file.txt", "r") as file:
data = file.readlines()
for line in data:

By R.S. Jadhav Page 19


Python Programming Chapter 3

word = line.split('_')
print (word)

OUTPUT:-
['Hello', 'World!']

Modifying file pointer position


In real-world applications, sometimes we need to change the file pointer
location externally since we may need to read or write the content at various
locations.

For this purpose, the Python provides us the seek() method which enables us to
modify the file pointer position externally.

The syntax to use the seek() method is given below.

Syntax: <file-ptr>.seek(offset[, from)

The seek() method accepts two parameters:

offset: It refers to the new position of the file pointer within the file.

from: It indicates the reference position from where the bytes are to be moved.
If it is set to 0, the beginning of the file is used as the reference position. If it is
set to 1, the current position of the file pointer is used as the reference position.
If it is set to 2, the end of the file pointer is used as the reference position.

Consider the following example:-

CODE:-

# open the file file2.txt in read mode


fileptr = open("file2.txt","r")

#initially the filepointer is at 0


print("The filepointer is at byte :",fileptr.read())

#changing the file pointer location to 10.


fileptr.seek(10);

By R.S. Jadhav Page 20


Python Programming Chapter 3

#tell() returns the location of the fileptr.


print("After reading, the filepointer is
at:",fileptr.read())

OUTPUT:-

The filepointer is at byte : HELLO_WORLD!

After reading, the filepointer is at: D!

CODE;-

with open('file2.txt','a+') as a:
a.seek(0)
print(a.read())
a.write("\nThis is append+ mode")
a.close()

OUTPUT:-

HELLO_WORLD!

HELLO_WORLD!

HELLO_WORLD!

HELLO_WORLD!

HELLO_WORLD!

By R.S. Jadhav Page 21


Python Programming Chapter 3

Python OS module
Renaming the file

The Python os module enables interaction with the operating system. The os
module provides the functions that are involved in file processing operations
like renaming, deleting, etc. It provides us the rename() method to rename the
specified file to a new name. The syntax to use the rename() method is given
below.

Syntax: rename(current-name, new-name)

The first argument is the current file name and the second argument is the
modified name. We can change the file name bypassing these two arguments.

CODE:-

import os
os.rename('file.txt','file2.txt')

OUTPUT:-

By R.S. Jadhav Page 22


Python Programming Chapter 3

Removing the file


The os module provides the remove() method which is used to remove the
specified file. The syntax to use the remove() method is given below.

Syntax: remove(file-name)

CODE:-
import os
os.remove('file2.txt')

OUTPUT:-

By R.S. Jadhav Page 23


Python Programming Chapter 3

Creating the new directory:-


The mkdir() method is used to create the directories in the current working
directory. The syntax to create the new directory is given below.

Syntax: mkdir(directory name)

CODE:-

import os
os.mkdir('New Folder')

OUTPUT:-

By R.S. Jadhav Page 24


Python Programming Chapter 3

The getcwd() method:-


This method returns the current working directory.

The syntax to use the getcwd() method is given below:

CODE:-

import os
print(os.getcwd())

OUTPUT:-

F:\COCSIT\B.Sc(CS)- TY(Python)\File_Handling

Changing the current working directory:-

The chdir() method is used to change the current working directory to a


specified directory.

The syntax to use the chdir() method is given below.

Syntax chdir("new-directory")
By R.S. Jadhav Page 25
Python Programming Chapter 3

CODE:-

import os
os.chdir("F:\\COCSIT\\B.Sc(CS)-
TY(Python)\\File_Handling\\New Folder")
print(os.getcwd())

OUTPUT:-

F:\COCSIT\B.Sc(CS)- TY(Python)\File_Handling\New Folder

Deleting directory
The rmdir() method is used to delete the specified directory.

The syntax to use the rmdir() method is given below.

Syntax os.rmdir(directory name)

CODE:-

OUTPUT:-

By R.S. Jadhav Page 26


Python Programming Chapter 3

After writing os.rmdir() line in our code:-

By R.S. Jadhav Page 27


Python Programming Chapter 3

 Reading data from CSV/EXCEL file in python


First of all, what is a CSV ?

1. CSV (Comma Separated Values) is a simple file format used to store


tabular data, such as a spreadsheet or database. A CSV file stores tabular
data (numbers and text) in plain text.

2. Each line of the file is a data record. Each record consists of one or more
fields, separated by commas.

3. The use of the comma as a field separator is the source of the name for
this file format.

4. For working CSV files in python, there is an inbuilt module called csv.

CODE:-

import csv
a = open('raw1.csv')
for i in a:
print(i)

raw1.csv file:-

OUTPUT:-

By R.S. Jadhav Page 28


Python Programming Chapter 3

USING with as FUNCTION:-

CODE:-

import csv

By R.S. Jadhav Page 29


Python Programming Chapter 3

with open('raw1.csv') as a:
for i in a:
print(i)
OUTPUT:-
Sno.,Name,Roll_No.

1,A,10

2,B,20

3,C,30

4,D,40

Reading CSV files:-


Python provides various functions to read csv file. We are describing few
method of reading function.

o Using csv.reader() function

In Python, the csv.reader() module is used to read the csv file. It takes each row
of the file and makes a list of all the columns.

CODE:-

import csv
filename = 'raw1.csv'
a = open(filename,'r')
b = csv.reader(a)
for i in b:
print(i)
OUTPUT:-

['Roll No', 'Name']


['1', 'A']
['2', 'B']
['3', 'C']
['4', 'D']

By R.S. Jadhav Page 30


Python Programming Chapter 3

CODE:-

# importing csv module


import csv

# csv file name


filename = "raw.csv"

# initializing the titles and rows list


fields = []
rows = []

# reading csv file


with open(filename, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)

# extracting field names through first row


fields = next(csvreader)

# extracting each data row one by one


for row in csvreader:
rows.append(row)

# get total number of rows


print("Total no. of rows: %d"%(csvreader.line_num))

# printing the field names


print('Field names are:' + ', '.join(field for field in
fields))

# printing first 5 rows


print('\nFirst 5 rows are:\n')
for row in rows[:5]:
# parsing each column of a row
for col in row:
print("%s"%col)

OUTPUT:-

By R.S. Jadhav Page 31


Python Programming Chapter 3

Total no. of rows: 6

Field names are:Roll No, Name

First 5 rows are:

Let us try to understand this piece of code.


with open(filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)
Here, we first open the CSV file in READ mode. The file object is named
as csvfile.
The file object is converted to csv.reader object. We save the csv.reader
object as csvreader.
fields = csvreader.next()
csvreader is an iterable object. Hence, .next() method returns the current
row and advances the iterator to the next row.

Since the first row of our csv file contains the headers (or field names), we
save them in a list called fields.

By R.S. Jadhav Page 32


Python Programming Chapter 3

for row in csvreader:


rows.append(row)
Now, we iterate through remaining rows using a for loop. Each row is
appended to a list called rows.

If you try to print each row, one can find that row is nothing but a list
containing all the field values.
print("Total no. of rows: %d"%(csvreader.line_num))
csvreader.line_num is nothing but a counter which returns the number of
rows which have been iterated.

 Writing to CSV file

CODE:-

# importing the csv module


import csv

# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']

# data rows of csv file


rows = [ ['A', 'COE', '2', '9.0'],
['B', 'COE', '2', '9.1'],
['C', 'IT', '2', '9.3'],
['D', 'SE', '1', '9.5'],
['E', 'MCE', '3', '7.8'],
['F', 'EP', '2', '9.1']]

# name of csv file


filename = "raw.csv"

# writing to csv file


with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)

# writing the fields


csvwriter.writerow(fields)

# writing the data rows

By R.S. Jadhav Page 33


Python Programming Chapter 3

csvwriter.writerows(rows)

OUTPUT:-

Let us try to understand the above code in pieces.


fields and rows have been already defined. fields is a list containing all the
field names. rows is a list of lists.
Each row is a list containing the field values of that row.
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
Here, we first open the CSV file in WRITE mode. The file object is named
as csvfile.
The file object is converted to csv.writer object. We save the csv.writer
object as csvwriter.
csvwriter.writerow(fields)
Now we use writerow method to write the first row which is nothing but
the field names.
csvwriter.writerows(rows)
We use writerows method to write multiple rows at once.

By R.S. Jadhav Page 34


Python Programming Chapter 3

 Pickling and Unpickling of Data

Python pickle module is used for serializing and de-serializing python object
structures. The process to converts any kind of python objects (list, dict, etc.)
into byte streams (0s and 1s) is called pickling or serialization or flattening or
marshalling. We can converts the byte stream (generated through pickling) back
into python objects by a process called as unpickling.
Why Pickle?: In real world sceanario, the use pickling and unpickling are
widespread as they allow us to easily transfer data from one server/system to
another and then store it in a file or database.
Precaution: It is advisable not to unpickle data received from an untrusted
source as they may pose security threat. However, the pickle module has no
way of knowing or raise alarm while pickling malicious data.
Only after importing pickle module we can do pickling and unpickling.
Importing pickle can be done using the following command −
import pickle
CODE:-
import pickle
mylist = ['a', 'b', 'c', 'd']
with open('raw1.pickle', 'wb') as a:
pickle.dump(mylist, a)

OUTPUT:-

By R.S. Jadhav Page 35


Python Programming Chapter 3

In the above code, list – “mylist” contains four elements (‘a’, ‘b’, ‘c’, ‘d’). We
open the file in “wb” mode instead of “w” as all the operations are done using
bytes in the current working directory.

A new file named “raw1.pickle” is created, which converts the mylist data in
the byte stream.

Unpickling of Data:-

CODE:-
import pickle
pickle_off = open ("raw1.pickle", "rb")
emp = pickle.load(pickle_off)
print(emp)

Output: On running above scripts, you can see your mylist data again as output.
['a', 'b', 'c', 'd']

Pickling is a way to convert a python object (list, dict, etc.) into a character
stream. The idea is that this character stream contains all the information
necessary to reconstruct the object in another python script

By R.S. Jadhav Page 36


Python Programming Chapter 3

Pickle a simple dictionary :-

CODE:-
import pickle
EmpID =
{1:"Zack",2:"53050",3:"IT",4:"38",5:"Flipkart"}
pickling_on = open("raw1.pickle","wb")
pickle.dump(EmpID, pickling_on)
pickling_on.close()

OUTPUT:-

Unpickle a dictionary :-

CODE:-
import pickle
pickle_off = open("raw1.pickle", 'rb')
EmpID = pickle.load(pickle_off)
print(EmpID)

OUTPUT:-

By R.S. Jadhav Page 37


Python Programming Chapter 3

On running above script(unpickle) we get our dictionary back as we initialized


earlier. Also, please note because we are reading bytes here, we have used “rb”
instead of “r”.

{1: 'Zack', 2: '53050', 3: 'IT', 4: '38', 5: 'Flipkart'}

Pickle Exceptions
Below are some of the common exceptions raised while dealing with pickle
module −
 Pickle.PicklingError: If the pickle object doesn’t support pickling, this
exception is raised.
 Pickle.UnpicklingError: In case the file contains bad or corrupted data.
 EOFError: In case the end of file is detected, this exception is raised.
Prons:
 Comes handy to save complicated data.
 Easy to use, lighter and doesn’t require several lines of code.
 The pickled file generated is not easily readable and thus provide some
security.
Cons:
 Languages other than python may not able to reconstruct pickled python
objects.
 Risk of unpickling data from malicious sources.

CODE:-
# Pickling without a file
import pickle
# initializing data to be stored in db
Omkar = {'key' : 'Omkar', 'name' : 'Omkar Pathak',
'age' : 21, 'pay' : 40000}
Jagdish = {'key' : 'Jagdish', 'name' : 'Jagdish Pathak',
'age' : 50, 'pay' : 50000}

# database
db = {}

By R.S. Jadhav Page 38


Python Programming Chapter 3

db['Omkar'] = Omkar
db['Jagdish'] = Jagdish

# For storing
b = pickle.dumps(db) # type(b) gives <class 'bytes'>

# For loading
myEntry = pickle.loads(b)
print(myEntry)

Advantages of using Pickle Module:

1. Recursive objects (objects containing references to themselves): Pickle


keeps track of the objects it has already serialized, so later references to the
same object won’t be serialized again. (The marshal module breaks for
this.)\

2. Object sharing (references to the same object in different places): This


is similar to self- referencing objects; pickle stores the object once, and
ensures that all other references point to the master copy. Shared objects
remain shared, which can be very important for mutable objects.

3. User-defined classes and their instances: Marshal does not support these
at all, but pickle can save and restore class instances transparently. The
class definition must be importable and live in the same module as when the
object was stored.

Python Functions
Python Functions is a block of related statements designed to perform a
computational, logical, or evaluative 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.
Functions can be both built-in or user-defined. It helps the program to be
concise, non-repetitive, and organized.
Syntax:
def function_name(parameters):
"""docstring"""

By R.S. Jadhav Page 39


Python Programming Chapter 3

statement(s)
return expression

Creating a Function

We can create a Python function using the def keyword.

Example: Python Creating Function

CODE;-
# A simple Python function

def fun():
print("Welcome to COCSIT")

Calling a Function
After creating a function we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.

Example: Python Calling Function

CODE:-
# A simple Python function

def fun():
print("Welcome to COCSIT")

# Driver code to call a function


fun()

OUTPUT:-
Welcome to COCSIT

Arguments of a Function
Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.

By R.S. Jadhav Page 40


Python Programming Chapter 3

Example: Python Function with arguments

In this example, we will create a simple function to check whether the number
passed as an argument to the function is even or odd.

CODE:-
# A simple Python function to check
# whether x is even or odd

def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)

OUTPUT:-
even
odd

Types of Arguments:-

Python supports various types of arguments that can be passed at the time of
the function call. Let’s discuss each type in detail.
Default arguments
A default argument is a parameter that assumes a default value if a value is not
provided in the function call for that argument. The following example
illustrates Default arguments.

CODE:-

By R.S. Jadhav Page 41


Python Programming Chapter 3

# Python program to demonstrate


# default arguments

def myFun(x, y=50):


print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only


# argument)
myFun(10)

OUTPUT:-

x: 10

y: 50

Keyword arguments
The idea is to allow the caller to specify the argument name with values so that
caller does not need to remember the order of parameters.
CODE:-
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='A', lastname='B')
student(lastname='B', firstname='A')

OUTPUT:-
A B
A B

Variable-length arguments

In Python, we can pass a variable number of arguments to a function using


special symbols. There are two special symbols:

By R.S. Jadhav Page 42


Python Programming Chapter 3

 *args (Non-Keyword Arguments)


 **kwargs (Keyword Arguments)

Example 1: Variable length non-keywords argument


CODE:-

# Python program to illustrate


# *args for variable number of arguments

def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'COCSIT')

OUTPUT:-

Hello

Welcome

to

COCSIT

Example 2: Variable length keyword arguments


CODE:-

# Python program to illustrate


# *kwargs for variable number of keyword arguments

def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

# Driver code
myFun(first='Hello', mid='Welcome', last='To Cocsit')

OUTPUT:-

By R.S. Jadhav Page 43


Python Programming Chapter 3

first == Hello

mid == Welcome

last == To Cocsit

Docstring

The first string after the function is called the Document string or Docstring in
short. This is used to describe the functionality of the function.

The use of docstring in functions is optional but it is considered a good


practice.
The below syntax can be used to print out the docstring of a function:
Syntax: print(function_name.__doc__)

Example: Adding Docstring to the function

CODE:-
# A simple Python function to check
# whether x is even or odd

def evenOdd(x):
"""Function to check if the number is even or odd"""

if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


print(evenOdd.__doc__)

OUTPUT:-

Function to check if the number is even or odd

By R.S. Jadhav Page 44


Python Programming Chapter 3

The return statement


The function return statement is used to exit from a function and go back to
the function caller and return the specified value or data item to the caller.
Syntax: return [expression_list]

The return statement can consist of a variable, an expression, or a constant


which is returned to the end of the function execution. If none of the above is
present with the return statement a None object is returned.

Example: Python Function Return Statement

CODE:-

def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))

OUTPUT:-

16

Is Python Function Pass by Reference or pass by value?

One important thing to note is, in Python every variable name is a reference.
When we pass a variable to a function, a new reference to the object is created.
Parameter passing in Python is the same as reference passing in Java.
CODE:-

# Here x is a new reference to same list lst


def myFun(x):
x[0] = 20

By R.S. Jadhav Page 45


Python Programming Chapter 3

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

OUTPUT:-
[20, 11, 12, 13, 14, 15]

When we pass a reference and change the received reference to something


else, the connection between the passed and received parameter is broken. For
example, consider the below program.

CODE;-
def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.
x = [20, 30, 40]

# Driver Code (Note that lst is not modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

OUTPUT:-
[10, 11, 12, 13, 14, 15]

Another example to demonstrate that the reference link is broken if we assign


a new value (inside the function).

CODE:-

def myFun(x):

# After below line link of x with previous


# object gets broken. A new object is assigned
# to x.

By R.S. Jadhav Page 46


Python Programming Chapter 3

x = 20

# Driver Code (Note that lst is not modified


# after function call.
x = 10
myFun(x)
print(x)

OUTPUT:-
10

Python Function within Functions

A function that is defined inside another function is known as the inner


function or nested function.
Nested functions are able to access variables of the enclosing scope. Inner
functions are used so that they can be protected from everything happening
outside the function.
CODE:-
# Python program to
# demonstrate accessing of
# variables of nested functions

def f1():
s = 'Hello World!!!!'

def f2():
print(s)

f2()

# Driver's code
f1()

OUTPUT:-
Hello World!!!!

By R.S. Jadhav Page 47


Python Programming Chapter 3

 Using Python Libraries


WHAT IS A LIBRARY?

As mentioned above that a library is a collection of modules (and packages)


that together cas a specific type of applications or requirements. A library
can have multiple modules.

This will become clearer to you when we talk about what modules are in
coming lines Some commonly used Python libraries are as listed below

Python standard library :-

This library is distributed with Python that contains module for various types
of functionalities. Some commonly used modules of Python standard library
are:-

math module:- which provides mathematical functions to support different


types calculations

cmath module:- which provides mathematical functions for complex


numbers.

random module:- which provides functions for generating pseudo-ranidos


numbers

statistics module:- which provides mathematical statistics functions

Urllib module:- which provides URL handling functions so that you can
access websites from within your program

NumPy library:- This library provides some advance math functionalities


along with tools to create and manipulate numeric arrays.

SciPy library:- This is another useful library that offers algorithmic and
mathematical tools for scientific calculations.

tkinter library:- This library provides traditional Python user interface toolkit
and helps you to create userfriendly GUI interface for different types of
applications.

Matplotlib library:- This library offers many functions and tools to produce
quality output in variety of formats such as plots, charts, graphs etc.

By R.S. Jadhav Page 48


Python Programming Chapter 3

A library can have multiple modules in it. Let us know what a module
means

What is a Module ?

The act of partitioning a program into individual components (known as


modules) is called modularity. A module is a separate unit in itself.

The justification for partitioning a program is

it reduces its complexity to some degree and

it creates a number of well defined documented boundaries within the


program.
Another useful feature of having modules, is that its contents can be reused in
other programs, without having to rewrite or recreate them.

Structure of a Python Module:-

A Python module can contain much more than just functions.

A Python module is a normal Python file (.py file) containing one or more of
the following objects related to a particular task.

docstrings :- triple quoted comments; useful for documentation purposes. For


documentation, the docstrings should be the first string stored inside a
module/function - body/class

variables and constants:- labels for data

classes :- templates/blueprint to create objects of a certain kind.

Objects:- instances of classes. In general, objects are representation of some


abstract entity

statements:- instructions

functions:- named group of instructions

By R.S. Jadhav Page 49


Python Programming Chapter 3

 Python Classes and Objects

 A class is a user-defined blueprint or prototype from which objects are


created. Classes provide a means of bundling data and functionality
together.
 Creating a new class creates a new type of object, allowing new
instances of that type to be made. Each class instance can have attributes
attached to it for maintaining its state. Class instances can also have
methods (defined by their class) for modifying their state.
 To understand the need for creating a class let’s consider an example,
let’s say you wanted to track the number of students that may have
different attributes like name, age.
 If a list is used, the first element could be the student’s name while the
second element could represent its age.
 Let’s suppose there are 100 different students, then how would you
know which element is supposed to be which? What if you wanted to
add other properties to these students? This lacks organization and it’s
the exact need for classes.
 Class creates a user-defined data structure, which holds its own data
members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an
object.
Some points on Python class:
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator.
Eg.: Myclass.Myattribute

Class Definition Syntax:


class ClassName:
# Statement-1
.
.
.
# Statement-N

CODE:-
# Python3 program to
# demonstrate defining
# a class

By R.S. Jadhav Page 50


Python Programming Chapter 3

class Student:
pass

In the above example, the class keyword indicates that you are creating a class
followed by the name of the class (Student in this case).

Class Objects
An Object is an instance of a Class. A class is like a blueprint while an
instance is a copy of the class with actual values.
It’s not an idea anymore, it’s an actual student, like a student of name A who’s
seventeen years old. You can have many students to create many different
instances, but without the class as a guide, you would be lost, not knowing
what information is required.

An object consists of :
 State: It is represented by the attributes of an object. It also reflects the
properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
 Identity: It gives a unique name to an object and enables one object to
interact with other objects.

Declaring Objects (Also called instantiating a class)


When an object of a class is created, the class is said to be instantiated. All the
instances share the attributes and the behavior of the class.
But the values of those attributes, i.e. the state are unique for each object. A
single class may have any number of instances.

CODE:-
# Python3 program to
# demonstrate instantiating
# a class

class Student:

# A simple class
# attribute

By R.S. Jadhav Page 51


Python Programming Chapter 3

attr1 = "A"
attr2 = "B"

# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)

# Driver code
# Object instantiation
obj1 = Student()

# Accessing class attributes


# and method through objects
print("Calling attribute using object 1: ",obj1.attr1)
obj1.fun()

OUTPUT:-
Calling attribute using object 1: A
I'm a A
I'm a B

The self

 Class methods must have an extra first parameter in the method definition.
We do not give a value for this parameter when we call the method, Python
provides it.
 If we have a method that takes no arguments, then we still have to have one
argument.
 This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is
automatically converted by Python into MyClass.method(myobject, arg1,
arg2) – this is all the special self is about.

__init__ method

The __init__ method is similar to constructors in C++ and Java. Constructors


are used to initializing the object’s state. Like methods, a constructor also
contains a collection of statements(i.e. instructions) that are executed at the
time of Object creation. It runs as soon as an object of a class is instantiated.
The method is useful to do any initialization you want to do with your object.

By R.S. Jadhav Page 52


Python Programming Chapter 3

CODE:-

# A Sample class with init method


class Person:

# init method or constructor


def __init__(self, name):
self.name = name

# Sample Method
def myfun(self):
print('Hello, my name is', self.name)

p = Person('AB')
p.myfun()

Class and Instance Variables

Instance variables are for data, unique to each instance and class variables are
for attributes and methods shared by all instances of the class. Instance
variables are variables whose value is assigned inside a constructor or method
with self whereas class variables are variables whose value is assigned in the
class.
Defining instance variable using a constructor.

CODE:-
# Python3 program to show that the variables with a value
# assigned in the class declaration, are class variables
and
# variables inside methods and constructors are instance
# variables.

# Class for Student


class Student:

# Class Variable
person = 'student'

# The init method or constructor

By R.S. Jadhav Page 53


Python Programming Chapter 3

def __init__(self, name, age):

# Instance Variable
self.name = name
self.age = age

# Objects of Dog class


obj1 = Student("A", 20)
obj2 = Student("B", 30)

print('Obj1 details:')
print('Obj1 is a', obj1.person)
print('Name: ', obj1.name)
print('Age: ', obj1.age)

print('\nObj2 details:')
print('Obj2 is a', obj2.person)
print('Name: ', obj2.name)
print('Age: ', obj2.age)

# Class variables can be accessed using class


# name also
print("\nAccessing class variable using class name")
print(Student.person)

OUTPUT:-

Obj1 details:
Obj1 is a student
Name: A
Age: 20

Obj2 details:
Obj2 is a student
Name: B
Age: 30

Accessing class variable using class name


student

By R.S. Jadhav Page 54


Python Programming Chapter 3

 Constants of Maths in Python

Math module is a standard in-built module in Python that can be used for
performing the mathematical tasks. The math module has a set of methods and
constants.
Note: For more information, refer to Math-library-functions

1. Python math.e constant: The math.e constant returns the Euler’s


number: 2.71828182846.

Syntax: math.e
Returns: Return a float value, 2.71828182846, representing the mathematical c
onstant e

Example:

# Import math Library

import math

# Print the value of Euler e

print (math.e)

Output:
2.718281828459045
2. Python math.pi constant: The math.pi constant returns the value pi:
3.14159265359. It is defined as the ratio of the circumference to the diameter of
a circle.

Syntax: math.pi
Returns: A float value, 3.14159265359, representing the mathematical constan
t PI
Example:

# Import math Library

import math

# Print the value of pi

print (math.pi)

By R.S. Jadhav Page 55


Python Programming Chapter 3

Output:
3.141592653589793

3. Python math.tau constant: The math.tau constant returns the value tau:
6.283185307179586. It is defined as the ratio of the circumference to the radius
of a circle.

Syntax: math.tau
Returns: A float value, 6.283185307179586, representing the mathematical con
stant tau
Example:

# Import math Library

import math

# Print the value of tau

print (math.tau)

Output:
6.283185307179586
4. Python math.inf constant: The math.inf constant returns of positive infinity.
For negative infinity, use -math.inf.The inf constant is equivalent to float(“inf”).

Syntax: math.inf
Returns: A float value, returns the value of positive infinity.
Example:

# Import math Library

import math

# Print the positive infinity

print (math.inf)

# Print the negative infinity

print (-math.inf)

Output:
inf

By R.S. Jadhav Page 56


Python Programming Chapter 3

-inf
5. Python math.nan constant: The math.nan constant returns a floating-point
nan (Not a Number) value. This value is not a legal number.The nan constant is
equivalent to float(“nan”).

Syntax: math.nan
Returns: A float value, nan (Not a Number)
Example:

# Import math Library

import math

# Print the value of nan

print (math.nan)

Output:
nan

By R.S. Jadhav Page 57

You might also like