Python Programming Chapter 3
Python Programming Chapter 3
Python Programming Chapter 3
Python 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)
OUTPUT:-
I'm a AB
Hello
Cocsit
Latur
CODE:-
String1 = "HELLOCOCSITLATUR"
print("Initial String: ")
print(String1)
OUTPUT:-
Initial String:
HELLOCOCSITLATUR
String Slicing
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])
OUTPUT:-
Initial String:
HELLOCOCSITLATUR
Start Index:
COCSITLATUR
End Index:
HELLOCOCS
LOCOCSITL
LOCOCSITLAT
CODE:-
OUTPUT:-
Variable as string = 15
Variable as integer = 15
Variable as hexadecimal = f
Variable as octal = 17
Hello World!
Value of A: 10
CODE:-
OUTPUT:-
You can use multiple format conversion types in a single print statement
CODE:-
variable = 20
print (string)
OUTPUT:-
Variable as integer = 20
Variable as float = 20.000000
The .format() method has many advantages over the placeholder method:
We can insert object by using index-based position
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:-
a: 1, b: Two, c: 12.3
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:-
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
Modifying String:-
Python strings are immutable
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'
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_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+.
ABCDEF
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.
CODE:-
a = open('file.txt','r')
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!
The open command will open the file in the read mode and the for loop will
print each line present in the file.
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
lo_
Worl
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:-
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:-
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!
CODE:-
with open('file.txt','w') as a:
a.write("This is a write function")
a.write('''
This will override
existing data
''')
OUTPUT:-
word = line.split('_')
print (word)
OUTPUT:-
['Hello', 'World!']
For this purpose, the Python provides us the seek() method which enables us to
modify the file pointer position externally.
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.
CODE:-
OUTPUT:-
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!
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.
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:-
Syntax: remove(file-name)
CODE:-
import os
os.remove('file2.txt')
OUTPUT:-
CODE:-
import os
os.mkdir('New Folder')
OUTPUT:-
CODE:-
import os
print(os.getcwd())
OUTPUT:-
F:\COCSIT\B.Sc(CS)- TY(Python)\File_Handling
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:-
Deleting directory
The rmdir() method is used to delete the specified directory.
CODE:-
OUTPUT:-
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:-
CODE:-
import csv
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
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:-
CODE:-
OUTPUT:-
Since the first row of our csv file contains the headers (or field names), we
save them in a list called fields.
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.
CODE:-
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
csvwriter.writerows(rows)
OUTPUT:-
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:-
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
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:-
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 = {}
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)
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"""
statement(s)
return expression
Creating a 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.
CODE:-
# A simple Python function
def fun():
print("Welcome to COCSIT")
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.
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")
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:-
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
def myFun(*argv):
for arg in argv:
print(arg)
OUTPUT:-
Hello
Welcome
to
COCSIT
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:-
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.
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")
OUTPUT:-
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
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:-
OUTPUT:-
[20, 11, 12, 13, 14, 15]
CODE;-
def myFun(x):
OUTPUT:-
[10, 11, 12, 13, 14, 15]
CODE:-
def myFun(x):
x = 20
OUTPUT:-
10
def f1():
s = 'Hello World!!!!'
def f2():
print(s)
f2()
# Driver's code
f1()
OUTPUT:-
Hello World!!!!
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
This library is distributed with Python that contains module for various types
of functionalities. Some commonly used modules of Python standard library
are:-
Urllib module:- which provides URL handling functions so that you can
access websites from within your program
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.
A library can have multiple modules in it. Let us know what a module
means
What is a Module ?
A Python module is a normal Python file (.py file) containing one or more of
the following objects related to a particular task.
statements:- instructions
CODE:-
# Python3 program to
# demonstrate defining
# a class
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.
CODE:-
# Python3 program to
# demonstrate instantiating
# a class
class Student:
# A simple class
# attribute
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()
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
CODE:-
# Sample Method
def myfun(self):
print('Hello, my name is', self.name)
p = Person('AB')
p.myfun()
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 Variable
person = 'student'
# Instance Variable
self.name = name
self.age = age
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)
OUTPUT:-
Obj1 details:
Obj1 is a student
Name: A
Age: 20
Obj2 details:
Obj2 is a student
Name: B
Age: 30
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
Syntax: math.e
Returns: Return a float value, 2.71828182846, representing the mathematical c
onstant e
Example:
import math
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
print (math.pi)
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
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
print (math.inf)
print (-math.inf)
Output:
inf
-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
print (math.nan)
Output:
nan