We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 9
Difference between List, Tuples and dictionary:
List
Tuples
Dictionary
Alist is mutable
A tuple is immutable
Adictionary is mutable
Lists are dynamic
Tuples are fixed size in nature
In values can be of any
data type and can
repeat, keys must be of
immutable type
List = [10, 12, 15]
Words = ("spam’, "egss”)
Or
List are enclosed in | Tuples are enclosed in parenthesis () | Tuples are enclosed in
brackets ] and their | and cannot be updated curly braces {} and
elements and size consist of key:value
can be changed
Homogenous Heterogeneous Homogenous
Example: Example: Example:
Dict = {"ram": 26, "abi":
24}
Words = “spam”, “eggs”
Access: Access:
print(words[0}) print(dict{"ram"])
Can contain duplicate
Can contain duplicate elements.
Cant contain duplicate
doesnt need random
access.
* List is used when
data can be modified
frequently
“ Atuple is used in combination
with a dictionary Lea tuple might
represent a key.
elements Faster compared to lists keys, but can contain
duplicate values
Slicing canbe done _| Slicing can be done Slicing can’t be done
Usage: "4 Usage:
+ Listisusedifa | ¢ Tuplecan be used when data * Dictionary is used
collection of data that | cannot be changed. when a logical
association between
key:value pair.
+ When in need of fast
lookup for data, based
ona custom key.
+ Dictionary is used
when data is being
constantly modified.a
TH
KINGSTON
Unit -5
FILES
File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When
we are done, it needs to be closed, so that resources that are tied with the file
are freed. Hence, in Python, a file operation takes place in the following order.
1. Open afile
2. Read or write (perform operation)
3. Close the file
Opening a file
Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python33/README. txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we
want to read 'r', write 'w' or append ‘a’ to the file. We also specify if we want
to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading
from the file. On the other hand, binary mode returns bytes and this is the
mode to be used when dealing with non-text files like image or exe files.
Python File ModesMode : Description
‘t's Open a file for reading. (default)
‘w': Open a file for writing. Creates a new file if it does not exist or truncates
the file if it exists,
'x' : Open a file for exclusive creation. If the file already exists, the operation
fails.
‘a! : Open for appending at the end of the file without truncating it. Creates a
new file if it does not exist.
‘t's Open in text mode. (default)
‘b': Open in binary mode.
‘+! Open a file for updating (reading and w
{= open("test.txt") # equivalent to 'r' or ‘rt’
f= open(“test.txt", 'w') # write in text mode
f= open("img.bmp",'r+b') # read and write in binary mode
Hence, when working with files in text mode, it is highly recommended to
specify the encoding type.
f= open(“test.txt",mode = 'r',encoding = ‘utf-8')
Closing a File
When we are done with operations to the file, we need to properly close it.
Closing a file will free up the resources that were tied with the file and is done
using the close() method.
Python has a garbage collector to clean up unreferenced objects but, we must
not rely on it to close the file.
f= open\"test.txt" encoding = ‘utf-8')
# perform file operations
ficlose()ait
KanastoN
This method is not entirely safe. If an exception occurs when we are
performing some operation with the file, the code exits without closing the
file. A safer way is to use a try...finally block.
try:
fr open("test.txt",encoding = ‘utf-8')
# perform file operations
finally:
ficlose()
Reading and writing
A text file is a sequence of characters stored on a permanent medium like a
hard drive, flash memory, or CD-ROM.
To write a file, you have to open it with mode ‘w' as a second parameter:
>>> fout = openf‘output. txt’, 'w')
>>> print fout
If the file already exists, opening it in write mode clears out the old data and
starts fresh, so be carefull If the file doesn’t exist, a new one is created.
The write method puts data into the file.
>>> line1 = "This here's the wattle,\n”
>>>fout.write(line1)
Again, the file object keeps track of where it is, so if you call write again, it adds
the new data to the end.
>>> line2 = "the emblem of our land.\n"
>>> fout.write(line2)
When you are done writing, you have to close the file.
>>> fout.close()zeit
KINGSTON
Format operator
The argument of write has to be a string, so if we want to put other values in a
file, we have to convert them to strings. The easiest way to do that is with str:
>>> x=52
>>> fout.write(str(x))
An alternative is to use the format operator, %. When applied to integers, % is
the modulus operator. But when the first operand is a string, % is the format
operator.
The first operand is the format string, which contains one or more format
sequences, which specify how the second operand is formatted. The result is a
string.
For example, the format sequence '%d' means that the second operand should
be formatted as an integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
42"
EXCEPTION
Python (interpreter) raises exceptions when it encounters errors. Error caused by
not following the proper structure (syntax) of the language is called syntax error
or parsing error.
>>> ffa<3
File "", tine 1
ifa<3
SyntaxError: invalid syntaxKINGSTON
Errors can also occur at runtime and these are called exceptions. They occur, for
example, when a file we try to open does not exist (FileNotFoundError),
dividing a number by zero (ZeroDivisionError), module we try to import is not
found (ImportError) ete.
Whenever these type of runtime error occur, Python creates an exception object.
If not handled properly, it prints a traceback to that error along with some
details about why that error occurred.
>>> 1/0
Traceback (most recent call last):
File "", line 301, in runcode
File "", line 1, in
ZeroDivisionError: division by zero
>>> open("imaginary.txt")
Traceback (most recent call last):
File "", line 301, in runcode
File "", line 1, in
FileNotFoundError: [Errno 2] No such file or directory
‘imaginary.tx
Python Exception Handling
Python has many built-in exceptions which forces your program to output an
error when something in it goes wrong.
When these exceptions occur, it causes the current process to stop and passes it
to the calling process until it is handled. If not handled, our program will crash.
For example, if function A calls function B which in turn calls function C and
an exception occurs in function C. If it is not handled in C, the exception passes
to B and then to A.
If never handled, an error message is spit out and our program come to a
sudden, unexpected halt.atir
KINGsTON
In Python, exceptions can be handled using a try statement.
A critical operation which can raise exception is placed inside the try clause and
the code that handles exception is written in except clause.
It is up to us, what operations we perform once we have caught the exception.
Here is a simple example.
MODULES
Any file that contains Python code can be imported as a module. For example,
suppose you have a file named we.py with the following code:
def linecount(filename):
0
for line in open(filename):
count
count += 1
return count
print linecount(‘wepy')
If you run this program, it reads itself and prints the number of lines in the file,
which is 7.
You can also import it like this:
>>> import we
7aftr
KINGSTON
Now you have a module object we:
>>> print we
>>> welinecount( wepy')
7
So that’s how you write modules in Python.
The only problem with this example is that when you import the module it
executes the test code at the bottom. Normally when you import a module, it
defines new functions but it doesn’t execute them.
Programs that will be imported as modules often use the following idios
_name__ == '_main__':
print linecount{'we.py')
__name__ is a built-in variable that is set when the program starts. If the
program is running as a script, —_name__ has the value __main__; in that case,
the test code is executed. Otherwise, if the module is being imported, the test
code is skipped.
Eg:
#import module import calendar
2017
mn = 8
#To ask month and year from the user
#
#mun = int(input("Enter month: "))
= int(input("Enter year: "))
display the calendar
print(calendar.month(yy, mm))atic
KINGsTON
PACKAGE
A package is a collection of modules. A Python
packages and modules.
ackage can have
A directory must contain a file named _i
consider it as a pa
initial
\_-py in order for Python to
kage. This file can be left empty but we generally place the
zation code for that package in this file.
Here is an example. Suppose we are developing a game, one possible
organization of packages and modules could be as shown in the figure below.
[cane
(Come) [Coy] [iano
a a
4 plover ‘ctongepy] [ tay |
Frawesr | | conmpy | | ovray
Importing module from a package
We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above example, it is
done as follows. import Game.level.start
Now if this module contains a function named select_difficulty(), we must use
the full name to reference it.
Game.Level.start.select_difficulty(2)
If this construct seems lengthy, we can import the module without the package
prefix as follows.
from Gome.tevel import start
ki ft
We can now call the function simply as follows.
start.select_difficulty(2)