Python Notes Unit - III
Python Notes Unit - III
T) SEM - III
1-Python Lists
Introduction
The most basic data structure in Python is the sequence.
Each element of a sequence is assigned a number - its position or index. The first index is zero,
the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples.
Python Lists
The list is a most versatile datatype available in Python which can be 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.
For example –
#!/usr/bin/python
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Compiled by : Prof. Mohd. Shahid Subject : Python Programming Class : SYBSc(I.T) SEM - III
You can update single or multiple elements of lists by giving the slice on the left-hand side of the
assignment operator, and you can add to elements in a list with the append() method. For
example −
#!/usr/bin/python
Result :
Value available at index 2 :
1997
New value available at index 2 :
2001
#!/usr/bin/python
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1
In fact, lists respond to all of the general sequence operations we used on strings in the prior
chapter.
2-Python Tuples
Introduction
• A tuple is a sequence of immutable Python objects.
• 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.
• Optionally you can put these comma-separated values between parentheses also. For
example −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is
only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
#!/usr/bin/python
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
• 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 as the following
example demonstrates −
#!/usr/bin/python
There is, of course, nothing wrong with putting together another tuple with the undesired
elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example:
#!/usr/bin/python
print tup
del tup;
print "After deleting tup : "
print tup
Compiled by : Prof. Mohd. Shahid Subject : Python Programming Class : SYBSc(I.T) SEM - III
This produces the following result. Note an exception raised, this is because after del tup tuple
does not exist any more –
In fact, tuples respond to all of the general sequence operations we used on strings in the prior
chapter −
5 tuple(seq)
3-Python Dictionary
Introduction
• Each key is separated from its value by a colon (:), the items are separated by commas,
and the whole thing is enclosed in curly braces.
• An empty dictionary without any items is written with just two curly braces, like this: {}.
• Keys are unique within a dictionary while values may not be.
• The values of a dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.
#!/usr/bin/python
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error
as follows –
#!/usr/bin/python
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
Compiled by : Prof. Mohd. Shahid Subject : Python Programming Class : SYBSc(I.T) SEM - III
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing
entry, or deleting an existing entry as shown below in the simple example −
#!/usr/bin/python
dict['Age']: 8
dict['School']: DPS School
To explicitly remove an entire dictionary, just use the del statement. Following is a simple
example −
#!/usr/bin/python
This produces the following result. Note that an exception is raised because after del dict
dictionary does not exist any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Compiled by : Prof. Mohd. Shahid Subject : Python Programming Class : SYBSc(I.T) SEM - III
(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When
duplicate keys encountered during assignment, the last assignment wins. For example −
#!/usr/bin/python
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary
keys but something like ['key'] is not allowed. Following is a simple example:
#!/usr/bin/python
Gives the total length of the dictionary. This would be equal to the number of items in the
dictionary.
3 str(dict)
Returns the type of the passed variable. If passed variable is dictionary, then it would return
a dictionary type.
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
#!/usr/bin/python
• raw_input
• input
#!/usr/bin/python
This prompts you to enter any string and it would display same string on the screen. When I
typed "Hello Python!", its output is like this −
#!/usr/bin/python
This would produce the following result against the entered input −
Python provides basic functions and methods necessary to manipulate files by default. You can
do most of the file manipulation using a file object.
Syntax
file object = open(file_name [, access_mode][, buffering])
• file_name: The file_name argument is a string value that contains the name of the file
that you want to access.
• access_mode: The access_mode determines the mode in which the file has to be opened,
i.e., read, write, append, etc. A complete list of possible values is given below in the
table. This is optional parameter and the default file access mode is read (r).
• buffering: If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file. If you specify the buffering
value as an integer greater than 1, then buffering action is performed with the indicated
buffer size. If negative, the buffer size is the system default(default behavior).
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of
the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed at
the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file
if the file exists. If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.
Compiled by : Prof. Mohd. Shahid Subject : Python Programming Class : SYBSc(I.T) SEM - III
Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.softspace Returns false if space explicitly required with print, true otherwise.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
Python automatically closes a file when the reference object of a file is reassigned to another file.
It is a good practice to use the close() method to close a file.
Syntax
fileObject.close();
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
The write() method does not add a newline character ('\n') to the end of the string −
Compiled by : Prof. Mohd. Shahid Subject : Python Programming Class : SYBSc(I.T) SEM - III
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
The above method would create foo.txt file and would write given content in that file and finally
it would close that file. If you would open this file, it would have following content.
Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This method starts
reading from the beginning of the file and if count is missing, then it tries to read as much as
possible, maybe until the end of file.
Compiled by : Prof. Mohd. Shahid Subject : Python Programming Class : SYBSc(I.T) SEM - III
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
To use this module you need to import it first and then you can call any related functions.
Syntax
os.rename(current_file_name, new_file_name)
Example
#!/usr/bin/python
import os
Syntax
os.remove(file_name)
Example
#!/usr/bin/python
import os
Directories in Python
All files are contained within various directories, and Python has no problem handling these too.
The os module has several methods that help you create, remove, and change directories.
Syntax
os.mkdir("newdir")
Example
#!/usr/bin/python
import os
Syntax
os.chdir("newdir")
Example
#!/usr/bin/python
import os
Syntax
os.getcwd()
Example
#!/usr/bin/python
import os
Syntax:
os.rmdir('dirname')
Compiled by : Prof. Mohd. Shahid Subject : Python Programming Class : SYBSc(I.T) SEM - III
Example
Following is the example to remove "/tmp/test" directory. It is required to give fully qualified
name of the directory, otherwise it would search for that directory in the current directory.
#!/usr/bin/python
import os
4-Python Exceptions
Introduction
Python provides two very important features to handle any unexpected error in your Python
programs and to add debugging capabilities in them −
• Exception Handling: This would be covered in this tutorial. Here is a list standard
Exceptions available in Python:
• Assertions: This would be covered in Assertions in Python
EXCEPTION DESCRIPTION
NAME
Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not point to any
object.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place for all numeric
types.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
EOFError Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
ImportError Raised when an import statement fails.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing
Ctrl+c.
LookupError Base class for all lookup errors.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
NameError Raised when an identifier is not found in the local or global namespace.
Compiled by : Prof. Mohd. Shahid Subject : Python Programming Class : SYBSc(I.T) SEM - III
Assertions in Python
• An assertion is a sanity-check that you can turn on or turn off when you are done with
your testing of the program.
• The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more
accurate, a raise-if-not statement). An expression is tested, and if the result comes up
false, an exception is raised.
• Assertions are carried out by the assert statement, the newest keyword to Python,
introduced in version 1.5.
• Programmers often place assertions at the start of a function to check for valid input, and
after a function call to check for valid output.
When it encounters an assert statement, Python evaluates the accompanying expression, which is
hopefully true. If the expression is false, Python raises an AssertionError exception.
If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError.
AssertionError exceptions can be caught and handled like any other exception using the try-
except statement, but if not handled, they will terminate the program and produce a traceback.
What is Exception?
• An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions.
• In general, when a Python script encounters a situation that it cannot cope with, it raises
an exception.
• An exception is a Python object that represents an error.
• When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can defend your program by
placing the suspicious code in a try: block. After the try: block, include an except: statement,
followed by a block of code which handles the problem as elegantly as possible.
Compiled by : Prof. Mohd. Shahid Subject : Python Programming Class : SYBSc(I.T) SEM - III
Syntax
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
• A single try statement can have multiple except statements. This is useful when the try
block contains statements that may throw different types of exceptions.
• You can also provide a generic except clause, which handles any exception.
• After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.
• The else-block is a good place for code that does not need the try: block's protection.
Example
This example opens a file, writes content in the, file and comes out gracefully because there is no
problem at all −
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
Example
This example tries to open a file where you do not have write permission, so it raises an
exception −
#!/usr/bin/python
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
You cannot use else clause as well along with a finally clause.
Example
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this will produce the
following result: