Unit 2_2
Unit 2_2
UNIT-II
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 1
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 2
Python String
Strings in python are surrounded by either single quotation marks, or
double quotation marks.
‘Powerful’ is same as “Powerful”
You can display a string literal with the print() function.
Assigning a string to a variable is done with the variable name followed by
an equal sign and the string:
a = "Hello“ or a = ’Hello’
You can assign a multiline string to a variable by using three quotes:
a = “ ” ” Python was designed for readability, and has some similarities
to the English language with influence from mathematics. “ “ ”
Or
a = ‘ ‘ ‘ Python was designed for readability, and has some similarities
to the English language with influence from mathematics. ‘ ‘ ‘
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 3
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.1
MCA-106, Python Programming
Python String
continued…
Strings are Arrays
• Like many other popular programming languages, strings in Python 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.
• String data types are immutable. Which means a string value cannot
be updated.
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 4
Python String
continued…
String functions or operations on strings:
• Looping Through a String
for x in “BVICAM":
print(x)
• String Length – len()
• Check String – returns boolean
txt = "The best things in life are free!"
print("free" in txt)
• Check if NOT - returns boolean
txt = "The best things in life are free!"
print("expensive" not in txt)
• Slicing
b = "Hello, World!"
print(b[2:5])
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 5
Python String
continued…
Upper Case – upper()
Lower Case – lower()
Remove whitespace – strip(), lstrip(), rstrip()
Replace String – str.replace(old_str, new_str)
Split String – str.split() , str.split(‘-’)
String Concatenation – plus(+) operator
Stings Appending – str1 +=str2
Deleting string – del str
count(str,beg,end)
find(str,beg,end)
index(str,beg,end)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 6
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.2
MCA-106, Python Programming
Python String
continued…
String Format - we can combine strings and numbers by using the
format method.
1. The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders { } are:
code= 106
txt = “Paper Code of Python Programming is MCA - { }"
print(txt.format(code))
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 7
Slice Operation
A substring of a string is called a Slice.
Stride refers to the number of characters to move forward after the first
character is retrieved from the string. The default value of stride is 1.
We can specify a negative value for the third argument. This is useful to
print the original string in reverse order.
print(str[ : : -1])
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 8
Slice Operation
Try this:
Str=‘PYTHON’
print(str[-1])
print(str[-6])
print(str[-2:])
print(str[ : -2])
print(str[ -5 : -2])
print(str[ : : -3])
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 9
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.3
MCA-106, Python Programming
Python String
continued…
ord() Function:
chr() Function:
print(chr(82))
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 10
String Comparison
This is done using the following operators:
==: This checks whether two strings are equal
!=: This checks if two strings are not equal
<: This checks if the string on its left is smaller than that on its right
<=: This checks if the string on its left is smaller than or equal to that
on its right
>: This checks if the string on its left is greater than that on its right
>=: This checks if the string on its left is greater than or equal to that
on its right
• String comparison in Python takes place character by character. That
is, characters in the same positions are compared from both the
strings.
• If the characters fulfill the given comparison condition, it moves to the
characters in the next position. Otherwise, it merely returns False.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 11
Iterating String
string_name = “Python String“
Index=0
While index < len(string_name)
letter= string_name[index]
print(letter)
index+=1
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 12
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.4
MCA-106, Python Programming
Sequence Type
Sequences allow you to store multiple values in an organized and
efficient manner. There are several sequence types: strings, lists and
tuples. Two most popular sequence types are lists and Tuples.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 13
Python Lists
Python lists
The list is written as a list of comma-separated values (items) between
square brackets.
Important thing about a list is that items in a list need not be of the same
type.
Creating a list is as simple as putting different comma-separated values
between square brackets
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 14
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.5
MCA-106, Python Programming
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 16
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 17
The sort() method uses ASCII values to sort the values in the list.
When one list is assigned to another list using the assignment operator(=),
then a new copy of list is NOT made. Instead, assignment makes the two
variables point to the same list in memory. This is known as aliasing.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 18
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.6
MCA-106, Python Programming
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 19
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 20
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 21
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.7
MCA-106, Python Programming
Python Tuples
Python Tuples
• A tuple is a collection of objects which ordered and immutable.
• Tuples are sequences, just like lists. The differences between tuples and lists
are, the tuples cannot be changed unlike lists and tuples use parentheses,
whereas lists use square brackets.
• Creating a tuple is as simple as putting different comma-separated values.
• Please note, Tuples are immutable which means you cannot update or
change the values of tuple elements. You are able to take portions of existing
tuples to create new tuples
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 22
Python Tuples
Tuple Assignment, Packing, and Unpacking
A literal tuple containing several items can be assigned to a single object:
tup1= ('physics', 'chemistry', 1997, 2000 )
When this occurs, it is as though the items in the tuple have been
“packed” into the object.
If that “packed” object is subsequently assigned to a new tuple, the
individual items are “unpacked” into the objects in the tuple:
(s1,s2,s3,s4) = tup1
When unpacking, the number of variables on the left must match the
number of values in the tuple
Python Tuples
• Advantages of Tuple over List
• Since tuples are quite similar to lists, both of them are used in similar
situations. However, there are certain advantages of implementing a
tuple over a list. Below listed are some of the main advantages:
• We generally use tuples for heterogeneous (different) data types and
lists for homogeneous (similar) data types.
• Since tuples are immutable, iterating through a tuple is faster than with
list. So there is a slight performance boost.
• Tuples that contain immutable elements can be used as a key for a
dictionary. With lists, this is not possible.
• If you have data that doesn't change, implementing it as tuple will
guarantee that it remains write-protected.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 24
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.8
MCA-106, Python Programming
Creating Python
Dictionary
Creating a Dictionary:
Dictionary_variable = { }
3. To create a dictionary with one or more key-value pairs, we can use dict() function.
The dict() function creates a dictionary from a sequence of key-value pairs:
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 26
Creating Python
Dictionary
4. Dictionary comprehension is another way of creating a dictionary. It is a syntactic
construct which creates a dictionary based on existing sequence:
The expression generates elements(values) of dictionary from items in the sequence that
satisfy the condition
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 27
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.9
MCA-106, Python Programming
Python Dictionary
continued…
Accessing Items
x = dict1.get(“Name”)
print(dict1[‘Name’])
If you try to access an item with a key, which is not specified in the dictionary, a KEyError is
generated.
Change Values
dict1[‘Name’] = ‘Aayush Khurana’
dict.update({“Course” : “MBA”})
Adding Items
dict1[‘Marks’] = 91
dict1.update({“City” : “New Delhi”})
*Dictionary is an associative array also known as hashes since any key of the dictionary
can be associated or mapped to a value.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 28
Python Dictionary
continued…
Removing Items
del dict1[“City”]
del dict1
To delete or remove all items in just one statement, use clear() function.
dict1.clear()
Python Dictionary
continued…
Copy a Dictionary
You cannot copy a dictionary simply by typing dict1 = dict2
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 30
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.10
MCA-106, Python Programming
Python Dictionary
continued…
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
My_Library ={
“Book1”: {
‘Title’: ‘Fundamentals of IT’,
‘Author’:’Kapoor’,
‘Publisher’:’TMH’,
‘Year’: 2006
},
“Book2”: {
‘Title’: ‘Introduction to Python Programming’,
‘Author’:’Timothy A. Budd’,
‘Publisher’: ‘S.Chand’,
‘Year’: 2016
},
“Book3”: {
‘Title’: ‘PL/’SQL Programming,
‘Author’:’Ivaan Bayross’,
‘Publisher’: ‘Pearson’,
‘Year’: 2010}
}
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 31
Python Dictionary
Methods
Method Description
clear() Removes all the elements from the dictionary
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 32
print(sorted(sales,key=sales.get))
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 33
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.11
MCA-106, Python Programming
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 34
Python Sets
• Sets are used to store multiple items in a single variable.
• Set is one of 4 built-in data types in Python used to store collections of data,
the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.
• A set is a collection which is both unordered and unindexed.
• The items in a set do not have a defined order. Set items can appear in a
different order every time you use them, and cannot be referred to by index or
key.
• Every set element is unique (no duplicates) and must be immutable (cannot be
changed). However, a set itself is mutable. We can add or remove items from
it.
• Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.
• The major advantage of using a set, as opposed to a list, is that it has a highly
optimized method for checking whether a specific element is contained in the
set. This is based on a data structure known as a hash table.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 35
It can have any number of items and they may be of different types
(integer, float, tuple, string etc.). But a set cannot have mutable elements
like lists, sets or dictionaries as its elements.
my_set={1,2,3}
print(my_set)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 36
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.12
MCA-106, Python Programming
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 37
my_set.add(2)
print(my_set)
my_set.update([2,3,4,5,6])
print(my_set)
my_set.update([2,3],(7,8,9))
print(my_set)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 38
my_set.discard(4)
print(my_set)
my_set.remove(4)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 39
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.13
MCA-106, Python Programming
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 40
for n in A:
print(n)
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 41
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 42
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.14
MCA-106, Python Programming
Every file is identified by its path, that begins from the root node or root folder. The
file path is also known as pathname.
1. Relative path
2. Absolute path
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 43
In a text file, each line of data ends with a newline character. Each file
ends with a special character called the end-of-file(EOF) marker.
2. Binary files – It may contain any type of data, encoded in binary form.
It includes file such as images, videos, zip files and other executable
programs.
Like text file, binary file also ends with an end-of-file(EOF) marker.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 44
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 45
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.15
MCA-106, Python Programming
• The default is reading in text mode. In this mode, we get strings when
reading from the file.
• On the other hand, binary mode “b” returns bytes and this is the mode
to be used when dealing with non-text files like images or executable
files.
f= open(“img.bmp”,’rb+’) # read and write in binary mode
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 46
• The close() command terminates all the resources in use and frees the
system of this particular program.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 47
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 48
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.16
MCA-106, Python Programming
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 49
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 50
Python Directory
Management
Directories are a way of storing, organizing, and separating the files on a
computer.
The directory that does not have a parent is called a root directory. The
way to reach the file is called the path.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 51
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.17
MCA-106, Python Programming
Python Directory
Management continues….
os and os.path Module
• The os module is used to handle files and directories in various ways.
It provides provisions to create/rename/delete directories. This allows
even to know the current working directory and change it to another. It
also allows one to copy files from one directory to another. The major
methods used for directory management is explained below.
Python Directory
Management continues….
Getting Current Working Directory (CWD):
• os.getcwd() can be used.
• It returns a string that represents the path of the current working directory.
• The method does not require any parameters to be passed.
Renaming a directory:
• os.rename() method is used to rename the directory.
• The parameters passed are old_name followed by new_name.
• If a directory already exists with the new_name passed, OSError will be raised
in case of both Unix and Windows.
• If a file already exists with the new_name, in Unix no error arises, the directory
will be renamed. But in Windows the renaming won’t happen and error will be
raised.
• os.renames(‘old_name’,’dest_dir:/new_name’) method works similar
to os.rename() but it moves the renamed file to the specified destination
directory(dest_dir).
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 53
Python Directory
Management continues….
Changing Current Working Directory (CWD):
• Every process in the computer system will have a directory associated
with it, which is known as Current Working Directory(CWD).
• os.chdir() method is used to change it.
• The parameter passed is the path/name of the desired directory to
which one wish to shift.
Listing the files in a directory
• A directory may contain sub-directories and a number of files in it. To
list them, os.listdir() method is used.
• It either takes no parameter or one parameter.
• If no parameter is passed, then the files and sub-directories of the
CWD is listed.
• If files of any other directory other than the CWD is required to be
listed, then that directory’s name/path is passed as parameter.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 54
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.18
MCA-106, Python Programming
Python Directory
Management continues….
Removing a directory
• os.rmdir() method is used to remove/delete a directory.
• The parameter passed is the path to that directory.
• It deletes the directory if and only if it is empty, otherwise raises an
OSError.
To check whether it is a directory:
• Given a directory name or Path, os.path.isdir(path) is used to validate
whether the path is a valid directory or not.
• It returns boolean values only. Returns true if the given path is a valid
directory otherwise false.
To get size of the directory:
• os.path.getsize(path_name) gives the size of the directory in bytes.
• OSError is raised if, invalid path is passed as parameter.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Professor – Unit 1 55
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Dr. Saumya, Assistant Prof. U1.19