Python - UNIT 4 PDF
Python - UNIT 4 PDF
Python - UNIT 4 PDF
UNIT 4
Syllabus
1
Scripting languages Python Programming
Introduction
3. Portability
We can move Python programs from one platform to another, and run it without
any changes.
It runs seamlessly on almost all platforms including Windows, Mac OS X and
Linux.
2
Scripting languages Python Programming
For example: Need to connect MySQL database on a Web server? We can use
MySQLdb library using import MySQLdb.
Standard libraries in Python are well tested and used by hundreds of people. So we
can be sure that it won't break our application.
7. Object-oriented
Everything in Python is an object. Object oriented programming (OOP) helps we
solve a complex problem intuitively.
With OOP, we are able to divide these complex problems into smaller sets by
creating objects.
Applications of Python
1. Web Applications
We can create scalable Web Apps using frameworks and CMS (Content Management
System) that are built on Python. Some of the popular platforms for creating Web Apps are:
Django, Flask, Pyramid, Plone, Django CMS.
Sites like Mozilla, Reddit, Instagram and PBS are written in Python.
There are numerous libraries available in Python for scientific and numeric
computing. There are libraries like: SciPy and NumPy that are used in general purpose
computing. And, there are specific libraries like: EarthPy for earth science, AstroPy for
Astronomy and so on.
Also, the language is heavily used in machine learning, data mining and deep learning.
3
Scripting languages Python Programming
Python is slow compared to compiled languages like C++ and Java. It might not be a
good choice if resources are limited and efficiency is a must.
However, Python is a great language for creating prototypes. For example: We can use
Pygame (library for creating games) to create wer game's prototype first. If we like the prototype,
we can use language like C++ to create the actual game.
It is a good language with a lot of features and capabilities. Yet, it's one of the easiest
language to learn because of its simple easy-to-use syntax.
1. Immediate mode
Typing python in the command line will invoke the interpreter in immediate mode. We can
directly type in Python expressions and press enter to get the output.
>>>
is the Python prompt. It tells us that the interpreter is ready for our input. Try typing in 1 + 1 and
press enter. We get 2 as the output. This prompt can be used as a calculator. To exit this mode
type exit() or quit() and press enter.
2. Script mode
This mode is used to execute Python program written in a file. Such a file is called a script.
Scripts can be saved to disk for future use. Python scripts have the extension .py, meaning that
the filename ends with .py.
4
Scripting languages Python Programming
To execute this file in script mode we simply write python helloWorld.py at the command
prompt.
We can use any text editing software to write a Python script file.
We just need to save it with the .py extension. But using an IDE can make our life a lot easier.
IDE is a piece of software that provides useful features like code hinting, syntax highlighting and
checking, file explorers etc. to the programmer for application development.
Using an IDE can get rid of redundant tasks and significantly decrease the time required for
application development.
Python Keywords
All the keywords except True, False and None are in lowercase and they must be written as it is.
The list of all the keywords are given below.
5
Scripting languages Python Programming
as elif if or yield
Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps
6
Scripting languages Python Programming
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
Note:
Python Statement
7
Scripting languages Python Programming
Instructions that a Python interpreter can execute are called statements. For example, a = 1 is an
assignment statement.
Multi-line statement
In Python, end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\). For example:
a=1+2+3+\
4+5+6+\
7+8+9
This is explicit line continuation. In Python, line continuation is implied inside parentheses ( ),
brackets [ ] and braces { }. For instance, we can implement the above multi-line statement as
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [ ]
and { }. For example:
colors = ['red',
'blue',
'green']
We could also put multiple statements in a single line using semicolons, as follows
a = 1; b = 2; c = 3
8
Scripting languages Python Programming
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends with the
first unindented line.
The amount of indentation is up to us, but it must be consistent throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an
example.
for i in range(1,11):
print(i)
if i==5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results into
Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes
the code more readable. For example:
if True:
print('Hello')
a=5
and
if True: print('Hello'); a = 5
both are valid and do the same thing. But the former style is clearer.
9
Scripting languages Python Programming
Python Comments
Single-line comments
It extends up to the newline character. Comments are for programmers for better understanding
of a program. Python Interpreter ignores comment.
#This is a comment
print('Hello')
Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example:
#and it extends
10
Scripting languages Python Programming
Another way of doing this is to use triple quotes, either ''' or """.
Variable
In most of the programming languages a variable is a named location used to store data
in the memory.
Each variable must have a unique name called identifier. It is helpful to think
of variables as container that holds data which can be changed later throughout
programming.
Non technically, we can suppose variable as a bag to store books in it and those books
can be replaced at any time.
In Python, variables do not need declaration to reserve memory space. The "variable declaration"
or "variable initialization" happens automatically when we assign a value to a variable.
website = "Apple.com"
print(website)
Apple.com
11
Scripting languages Python Programming
In the above program, we assigned a value Apple.com to the variable website. Then we print the
value assigned to website i.e Apple.com.
Note : Python is a type inferred language, it can automatically infer (know) Apple.com is a String
and declare website as a String.
website = "Apple.com"
# assigning a new variable to website
website = "Google.com"
print(website)
Google.com
In the above program, we assigned new value Google.com to website. Now, the new
value Google.com will replace the old value Apple.com. For the confirmation, we print website
and it will display new value Google.com.
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
5
3
12
Scripting languages Python Programming
If we want to assign the same value to multiple variables at once, we can do this as
x = y = z = "same"
print (x)
print (y)
print (z)
same
same
same
The second program assigns the same string to all the three variables x, y and z.
Constants
Non technically, we can think of constant as a bag to store some books and those books
cannot be replaced once placed inside the bag.
13
Scripting languages Python Programming
In Python, constants are usually declared and assigned on a module. Here, the module
means a new file containing variables, functions etc., which is imported to main file. Inside the
module, constants are written in all capital letters and underscores separating the words.
Create a constant.py
PI = 3.14
GRAVITY = 9.8
Create a main.py
import constant
print(constant.PI)
print(constant.GRAVITY)
3.14
9.8
In the above program, we create a constant.py module file. Then, we assign the constant
value to PI and GRAVITY. After that, we create a main.py file and import the constant module.
Finally, we print the constant value.
14
Scripting languages Python Programming
1. Create a name that makes sense. Suppose, vowel makes more sense than v.
2. Use camelCase notation to declare a variable. It starts with lowercase letter. For example:
myName
myAge
myAddress
PI
G
MASS
TEMP
snake_case
MACRO_CASE
camelCase
CapWords
15
Scripting languages Python Programming
Python provides numerous built-in functions that are readily available to us at the Python
prompt.
Some of the functions like input() and print() are widely used for standard input and
output operations respectively. Let us see the output section first.
We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later. An example use is given below.
The sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is sys.stdout(screen). Here
are an example to illustrate this.
print(1,2,3,4)
16
Scripting languages Python Programming
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&
Python Input
To allow flexibility we might want to take the input from the user. In Python, we have
the input() function to allow this. The syntax for input() is
input([prompt])
Enter a number: 10
>>> num
'10'
Here, we can see that the entered value 10 is a string, not a number. To convert this into a
number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0
17
Scripting languages Python Programming
This same operation can be performed using the eval() function. But it takes it further. It can
evaluate even expressions, provided the input is a string
>>> int('2+3')
>>> eval('2+3')
Python Import
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename
and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in
Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.
import math
print(math.pi)
Now all the definitions inside math module are available in our scope. We can also import some
specific attributes and functions only, using the from keyword. For example:
18
Scripting languages Python Programming
>>> pi
3.141592653589793
Python Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The
value that the operator operates on is called the operand.
For example:
>>> 2+3
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the
operation.
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.
19
Scripting languages Python Programming
x+y
+ Add two operands or unary plus
+2
x-y
- Subtract right operand from the left or unary minus
-2
/ Divide left operand by the right one (always results into float) x/y
x % y (remainder of
% Modulus - remainder of the division of left operand by the right
x/y)
x = 15
y=4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
20
Scripting languages Python Programming
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
Comparison operators
Comparison operators are used to compare values. It either returns True or False according to the
condition.
21
Scripting languages Python Programming
> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
Greater than or equal to - True if left operand is greater than or equal to the
>= x >= y
right
<= Less than or equal to - True if left operand is less than or equal to the right x <= y
x = 10
y = 12
# Output: x > y is False
print('x > y is',x>y)
# Output: x < y is True
print('x < y is',x<y)
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
# Output: x >= y is False
print('x >= y is',x>=y)
# Output: x <= y is True
print('x <= y is',x<=y)
Logical operators
22
Scripting languages Python Programming
x = True
y = False
# Output: x and y is False
print('x and y is',x and y)
# Output: x or y is True
print('x or y is',x or y)
# Output: not x is False
print('not x is',not x)
Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit,
hence the name.
23
Scripting languages Python Programming
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Assignment operators
24
Scripting languages Python Programming
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the
left.
There are various compound operators in Python like a += 5 that adds to the variable and later
assigns the same. It is equivalent to a = a + 5.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
25
Scripting languages Python Programming
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Integers, floating point numbers and complex numbers fall under Python numbers category.
They are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs to and
the isinstance() function to check if an object belongs to a particular class.
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
A floating point number is accurate up to 15 decimal places. Integer and floating points are
separated by decimal points. 1 is integer, 1.0 is floating point number.
26
Scripting languages Python Programming
Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary
part. Here are some examples.
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed within
brackets [ ].
We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts
form 0 in Python.
a = [5,10,15,20,25,30,35,40]
# a[2] = 15
27
Scripting languages Python Programming
>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]
List items can be given in one line separated by a character; in this case, the entire list can be
read using input(). You can then use a string method split(), which returns a list of strings
resulting after cutting the initial string by spaces. Example:
If you run this program with the input data of 1 2 3, the list a will be equal to ['1', '2', '3']. Note
that the list will consist of strings, not of numbers. If you want to get the list of numbers, you
have to convert the list items one by one to integers:
a = input().split()
for i in range(len(a)):
28
Scripting languages Python Programming
a[i] = int(a[i])
print(a)
print(a)
The method split() has an optional parameter that determines which string will be used as the
separator between list items. For example, calling the method split('.') returns the list obtained by
splitting the initial string where the character '.' is encountered:
a = '192.168.0.1'.split('.')
print(a)
In Python, you can display a list of strings using one-line commands. For that, the method join is
used; this method has one parameter: a list of strings. It returns the string obtained by
concatenation of the elements given, and the separator is inserted between the elements of the
list; this separator is equal to the string on which is the method applied.
If a list consists of numbers, you have to use the dark magic of generators. Here's how you can
print out the elements of a list, separated by spaces:
a = [1, 2, 3]
print(' '.join([str(i) for i in a]))
# the next line causes a type error,
# as join() can only concatenate strs
29
Scripting languages Python Programming
# print(' '.join(a))
However, if you are not a fan of dark magic, you can achieve the same effect using the loop for.
Generators
To create a list filled with identical items, you can use the repetition of list, for example:
n=5
a = [0] * n
print(a)
To create more complicated lists you can use generators: the expressions allowing to fill a list
according to a formula. The general form of a generator is as follows:
where variable is the ID of some variable, sequence is a sequence of values, which takes the
variable (this can be a list, a string, or an object obtained using the function range), expression —
some expression, usually depending on the variable used in the generator. The list elements will
be filled according to this expression.
a = [0 for i in range(5)]
print(a)
If you need to fill out a list of squares of numbers from 1 to n, you can change the settings
of range to range(1, n + 1):
n=5
a = [i ** 2 for i in range(1, n + 1)]
30
Scripting languages Python Programming
print(a)
And in this example the list will consist of lines read from standard input: first, you need to enter
the number of elements of the list (this value will be used as an argument of the function range),
second — that number of strings:
Slices
A[i:j:-1] slice i-j elements A[i], A[i-1], ..., A[j+1] (that is, changing the order of the elements).
A[i:j:k] cut with the step k: A[i], A[i+k], A[i+2*k],... . If the value of k<0, the elements come in
the opposite order.
Each of the numbers i or j may be missing, what means “the beginning of line” or “the end of
line"
Lists, unlike strings, are mutable objects: you can assign a list item to a new value. Moreover, it
is possible to change entire slices. For example:
A[2:4] = [7, 8, 9]
print(A)
Here we received a list [1, 2, 3, 4, 5], and then try to replace the two elements of the
slice A[2:4] with a new list of three elements. The resulting list is as follows: [1, 2, 7, 8, 9, 5].
A = [1, 2, 3, 4, 5, 6, 7]
A[::-2] = [10, 20, 30, 40]
31
Scripting languages Python Programming
print(A)
And here, the resulting list will be [40, 2, 30, 4, 20, 6, 10]. The reason is, A[::-2] is a list of
elements A[-1], A[-3], A[-5], A[-7], and that elements are assigned to 10, 20, 30, 40,
respectively.
If a discontinuous slice (i.e. a slice with a step k, k > 1) is assigned a new value, then the number
of elements in the old and new slices necessarily coincide, otherwise error ValueError occurs.
Operations on lists
The index of the first occurrence of element x in the list; in its absence generates an
A.index(x)
exception ValueError
Python Tuple
Tuple is an ordered sequence of items same as list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
32
Scripting languages Python Programming
Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically.
We can use the slicing operator [] to extract items but we cannot change its value.
t = (5,'program', 1+3j)
# t[1] = 'program'
# Generates error
t[0] = 10
Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent
strings. Multi-line strings can be denoted using triple quotes, ''' or """.
Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.
33
Scripting languages Python Programming
s = 'Hello world!'
# s[4] = 'o'
# s[6:11] = 'world'
# Generates error
s[5] ='d'
A slice gives from the given string one character or some fragment: substring or subsequence.
There are three forms of slices. The simplest form of the slice: a single character
slice S[i] gives ith character of the string. We count characters starting from 0. That is, if S =
'Hello', S[0] == 'H', S[1] == 'e', S[2] == 'l',S[3] == 'l', S[4] == 'o'. Note that in Python there is no
separate type for characters of the string. S[i] also has the type str, just as the source string.
If you specify a negative index, then it is counted from the end, starting with the number -1. That
is, S[-1] == 'o',S[-2] == 'l', S[-3] == 'l', S[-4] == 'e', S[-5] == 'H'.
String S H e l l o
34
Scripting languages Python Programming
If the index in the slice S[i] is greater than or equal to len(S), or less than -len(S), the following
error is caused IndexError: string index out of range.
Slices: substring
Slice with two parameters S[a:b] returns the substring of length b - a, starting with the character
at index a and lasting until the character at index b, not including the last one. For
example, S[1:4] == 'ell', and you can get the same substring using S[-4:-1]. You can mix positive
and negative indexes in the same slice, for example, S[1:-1] is a substring without the first and
the last character of the string (the slice begins with the character with index 1 and ends with an
index of -1, not including it).
Slices with two parameters never cause IndexError. For example, for S == 'Hello' the
slice S[1:5] returns the string 'ello', and the result is the same even if the second index is very
large, like S[1:100].
If you omit the second parameter (but preserve the colon), then the slice goes to the end of string.
For example, to remove the first character from the string (its index is 0) take the slice S[1:].
Similarly if you omit the first parameter, then Python takes the slice from the beginning of the
string. That is, to remove the last character from the string, you can use sliceS[:-1]. The
slice S[:] matches the string S itself.
Any slice of a string creates a new string and never modifies the original one. In Python strings
are immutable, i.e they cannot be changed as the objects. You can only assign the variable to the
new string, but the old one stays in memory.
In fact in Python there are no variables. There are only the names that are associated with any
objects. You can first associate a name with one object, and then — with another. Can several
names be associated with one and the same object.
35
Scripting languages Python Programming
s = 'Hello'
t = s # s and t point to the same string
t = s[2:4] # now t points to the new string 'll'
print(s) # prints 'Hello' as s is not changed
print(t) # prints 'll'
Slices: subsequence
If you specify a slice with three parameters S[a:b:d], the third parameter specifies the step, same
as for functionrange(). In this case only the characters with the following index are taken: a a +
d, a + 2 * d and so on, until and not including the character with index b. If the third parameter
equals to 2, the slice takes every second character, and if the step of the slice equals to -1, the
characters go in reverse order. For example, you can reverse a string like this: S[::-1]. Let's see
the examples:
s = 'abcdefg'
print(s[1])
print(s[-1])
print(s[1:3])
print(s[1:-1])
print(s[:3])
print(s[2:])
print(s[:-1])
print(s[::2])
print(s[1::2])
print(s[::-1])
A method is a function that is bound to the object. When the method is called, the method is
applied to the object and does some computations related to it. Methods are invoked
36
Scripting languages Python Programming
Method find() searches a substring, passed as an argument, inside the string on which it's called.
The function returns the index of the first occurrence of the substring. If the substring is not
found, the method returns -1.
s = 'Hello'
print(s.find('e'))
#1
print(s.find('ll'))
#2
print(s.find('L'))
# -1
Similarly, the method rfind() returns the index of the last occurrence of the substring.
s = 'abracadabra'
print(s.find('b'))
#1
print(s.rfind('b'))
#8
If you call find() with three arguments s.find(substring, left, right), the search is performed inside
the slice s[left:right]. If you specify only two arguments, like s.find(substring, left), the search is
performed in the slice s[left:], that is, starting with the character at index left to the end of the
string. Method s.find(substring, left, right) returns the absolute index, relatively to the whole
string s, and not to the slice.
37
Scripting languages Python Programming
print(s.find('bond', 12))
# 23
Method replace() replaces all occurrences of a given substring with another one.
Syntax: s.replace(old, new) takes the string S and replaces all occurrences of substring old with
the substring new. Example:
One can pass the third argument count, like this: s.replace(old, new, count). It makes replace() to
replace only first count occurrences and then stop.
This method counts the number of occurrences of one string within another string. The simplest
form is this one: s.count(substring). Only non-overlapping occurrences are taken into account:
print('Abracadabra'.count('a'))
#4
print(('aaaaaaaaaa').count('aa'))
#5
If you specify three parameters s.count(substring, left, right), the count is performed within the
slice s[left:right].
38
Scripting languages Python Programming
Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.
a = {5,2,3,1,4}
# printing set variable
print("a = ", a)
# data type of variable a
print(type(a))
We can perform set operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates.
>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}
Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [] does
not work.
>>> a = {1,2,3}
>>> a[1]
39
Scripting languages Python Programming
You can define a set as simple as by naming all of its elements in brackets. The only exception
is empty set, which can be created using the function set(). If set(..) has a list, a string or a tuple
as a parameter, it will return a set composed of its elements. For example,
A = {1, 2, 3}
A = set('qwerty')
print(A)
will print {'e', 'q', 'r', 't', 'w', 'y'} as the output.
A = {1, 2, 3}
B = {3, 2, 3, 1}
print(A == B)
Each element may enter the set only once. set('Hello') returns the set of four elements: {'H', 'e', 'l',
'o'}.
You can get the number of elements in the set using the function len.
You can also iterate over all the elements of the set (in an undefined order!) using the loop for:
40
Scripting languages Python Programming
You can check whether an element belongs to a set using the keyword in: expressions like a in
A return a value of type bool. Similarly there's the opposite operation not in. To add an element
to the set there is the method add:
A = {1, 2, 3}
print(1 in A, 4 not in A)
A.add(4)
There are two methods to remove an element from a set: discard and remove. Their behavior
varies only in case if the deleted item was not in the set. In this case the method discard does
nothing and the method remove throws exception KeyError.
Finally, pop removes one random element from the set and returns its value. If the set is
empty, pop generates the exception KeyError.
Operations on sets
A|B
Returns a set which is the union of sets A and B.
A.union(B)
A |= B
Adds all elements of array B to the set A.
A.update(B)
A&B
Returns a set which is the intersection of sets A and B.
A.intersection(B)
A &= B
Leaves in the set A only items that belong to the set B.
A.intersection_update(B)
41
Scripting languages Python Programming
A -= B
Removes all elements of B from the set A.
A.difference_update(B)
A ^= B
Writes in A the symmetric difference of sets A and B.
A.symmetric_difference_update(B)
A <= B
Returns true if A is a subset of B.
A.issubset(B)
A >= B
Returns true if B is a subset of A.
A.issuperset(B)
Python Dictionary
It is generally used when we have a huge amount of data. Dictionaries are optimized for
retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key:value. Key and value can be of any type.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use key to retrieve the respective value. But not the other way around.
42
Scripting languages Python Programming
d = {1:'value','key':2}
print(type(d))
print("d[1] = ", d[1]);
print("d['key'] = ", d['key']);
# Generates error
print("d[2] = ", d[2]);
Applying dictionaries
to count the number of some objects. In this case, you need to make a dictionary where
keys are objects and values are amounts.
the storage of any data associated with the object. The keys are objects, the values are
associated data. For example, if you want to determine month's sequence number by its
name, you can do it using the dictionary Num['January'] = 1; Num['February'] = 2; ....
setting the correspondence between the objects (for instance, «the parent—descendant»). The
key is the object and the value is the corresponding object.
if you need a simple array, but the maximum value of the index of the element is very large,
though not all the possible indexes will be used (so-called "sparse array"), you can use
associative array to save memory.
An empty dictionary can be created using the function dict() or an empty pair of curly
braces {} (this is actually the reason the curly braces cannot be used to create an empty set). To
create a dictionary with some set of initial values, you can use the following constructions:
43
Scripting languages Python Programming
The first two methods can only be used to create small dictionaries by listing all their
elements. In addition, in the second method, the keys are passed as named parameters of dict, so
in this case, the keys can only be strings, and only correct identificators. In the third and fourth
case, you can create large dictionaries, if transferred arguments are a ready-made list, which can
be obtained not only from by listing all the elements, but are built in any other way during the
execution of the program. In the third way the function dict needs to recieve a list where each
element is a tuple of two elements: key and value. The fourth method uses the function zip,
which needs to recieve two lists of equal length: a list of keys and list of values.
Basic operation: getting value of the element by its key. It is written exactly as for lists: A[key]. If
there is no element with specified key in the dictionary it raises the exception KeyError.
Another way to define the value based on a key is a method get: A.get(key). If there is no element
with the key get in the dictionary, it returns None. In the form with two arguments A.get(key,
val) method returns val, if an element with the key key is not in the dictionary.
To check if an element belongs to a dictionary operations in and not in are used, same as for sets.
To add a new item to the dictionary you just need to assign it with some value: A[key] = value.
To remove an item from the dictionary you can use del A[key] (operation raises an
exception KeyError if there is no such key in the dictionary.) Here are two safe ways to remove an
item from the dictionary.
44
Scripting languages Python Programming
In the first case, we preliminary check the presence of an element, then we catch and handle the
exception.
Another way to remove an item from the dictionary is the method pop: A.pop(key). This method
returns the value of the removed element and if the element with the given key is not in the
dictionary, an exception is raised. If the method popreceives a second parameter, than for the
missing element it will return the value of this parameter. This allows to organize safely the
removal of the element from the dictionary: A.pop(key, None).
Iterating dictionary
You can easily iterate through the keys of all items in the dictionary:
A = dict(zip('abcdef', list(range(6))))
for key in A:
print(key, A[key])
The following methods return representation of the elements of the dictionary. The
representations are similar to sets, but they change, if you change the values of the elements.
Method keys returns a representation of the keys of all elements, values returns a representation
of all values, and the method items returns a representation of all pairs (tuples) of keys and
values.
Thus, for a quick check whether the value val is among all the values of the dictionary A you
should use boolean condition val in A.values(). To loop through keys and variables, you can do
the following:
A = dict(zip('abcdef', list(range(6))))
for key, val in A.items():
print(key, val)
45
Scripting languages Python Programming
We can convert between different data types by using different type conversion functions like
int(), float(), str() etc.
>>> float(5)
5.0
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
46
Scripting languages Python Programming
>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
Decision making is required when we want to execute a code only if a certain condition is
satisfied.
if test expression:
statement(s)
47
Scripting languages Python Programming
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
In Python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.
num = 3
if num > 0:
num = -1
if num > 0:
3 is a positive number
This is always printed
48
Scripting languages Python Programming
When variable num is equal to 3, test expression is true and body inside body of if is executed.
If variable num is equal to -1, test expression is false and body inside body of if is skipped.
The print( ) statement falls outside of the if block (unindented). Hence, it is executed regardless
of the test expression.
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only when test
condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
Example of if...else
49
Scripting languages Python Programming
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
In the above example, when num is equal to 3, the test expression is true and body of if is
executed and body of else is skipped.
If num is equal to -5, the test expression is false and body of else is executed and body of if is
skipped.
If num is equal to 0, the test expression is true and body of if is executed and body of else is
skipped.
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
50
Scripting languages Python Programming
Only one block among the several if...elif...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
Example of if...elif...else
# In this program,
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
51
Scripting languages Python Programming
We can have a if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to
figure out the level of nesting. This can get confusing, so must be avoided if we can.
Output 1
Enter a number: 5
Positive number
52
Scripting languages Python Programming
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
The for loop in Python is used to iterate over a sequence or other iterable objects. Iterating over a
sequence is called traversal.
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
53
Scripting languages Python Programming
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)
The sum is 48
We can generate a sequence of numbers using range() function. range(10) will generate numbers
from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start,stop,step size). step size defaults to
1 if not provided.
This function does not store all the values in memory, it would be inefficient. So it remembers
the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list().
The following example will clarify this.
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
54
Scripting languages Python Programming
print(list(range(10)))
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
We can use the range() function in for loops to iterate through a sequence of numbers. It can be
combined with the len() function to iterate though a sequence using indexing. Here is an example.
for i in range(len(genre)):
I like pop
I like rock
I like jazz
A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.
55
Scripting languages Python Programming
break statement can be used to stop a for loop. In such case, the else part is ignored.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it
executes the block of code in the else and prints
No items left.
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.
56
Scripting languages Python Programming
We generally use this loop when we don't know beforehand, the number of times to iterate.
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True. After one iteration, the test expression is checked again.
This process continues until the test_expression evaluates to False.
Body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
57
Scripting languages Python Programming
Enter n: 10
The sum is 55
In the above program, the test expression will be True as long as our counter variable i is less
than or equal to n (10 in our program).
We need to increase the value of counter variable in the body of the loop. This is very important
(and mostly forgotten). Failing to do so will result in an infinite loop (never ending loop).
Same as that of for loop, we can have an optional else block with while loop as well.
The else part is executed if the condition in the while loop evaluates to False. The while loop can
be terminated with a break statement.
In such case, the else part is ignored. Hence, a while loop's else part runs if no break occurs and
the condition is false.
# Example to illustrate
# the use of else statement
# with the while loop
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
58
Scripting languages Python Programming
else:
print("Inside else")
Output
Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter variable to print the string Inside loop three times.
On the forth iteration, the condition in while becomes False. Hence, the else part is executed.
In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until test expression is false, but sometimes we wish to
terminate the current iteration or even the whole loop without checking test expression.
59
Scripting languages Python Programming
The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will terminate the
innermost loop.
Syntax of break
break
Output
s
t
r
The end
In this program, we iterate through the "string" sequence. We check if the letter is "i", upon
which we break from the loop. Hence, we see in our output that all the letters up till "i" gets
printed. After that, the loop terminates.
60
Scripting languages Python Programming
The continue statement is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration.
Syntax of Continue
continue
The working of continue statement in for and while loop is shown below.
if val == "i":
continue
print(val)
print("The end")
Output
s
t
r
n
g
The end
This program is same as the above example except the break statement has been replaced with
continue.
61
Scripting languages Python Programming
We continue with the loop, if the string is "i", not executing the rest of the block. Hence, we see
in our output that all the letters except "i" gets printed.
However, nothing happens when pass is executed. It results into no operation (NOP).
Syntax of pass
pass
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in
the future. They cannot have an empty body. The interpreter would complain. So, we use
the pass statement to construct a body that does nothing.
62
Scripting languages Python Programming
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
63
Scripting languages Python Programming
Example of a function
def greet(name):
parameter"""
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
>>> greet('Paul')
Hello, Paul. Good morning!
Note: Try running the above code into the Python shell to see the output.
Docstring
The first string after the function header is called the docstring and is short for documentation
string. It is used to explain in brief, what a function does.
64
Scripting languages Python Programming
In the above example, we have a docstring immediately below the function header. We generally
use triple quotes so that docstring can extend up to multiple lines. This string is available to us
as __doc__ attribute of the function.
For example:
>>> print(greet.__doc__)
This function greets to
the person passed into the
name parameter
The return statement is used to exit a function and go back to the place from where it was called.
Syntax of return
return [expression_list]
This statement can contain expression which gets evaluated and the value is returned. If there is
no expression in the statement or the return statement itself is not present inside a function, then
the function will return the None object.
For example:
>>> print(greet("May"))
Hello, May. Good morning!
None
65
Scripting languages Python Programming
Example of return
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
Scope of a variable is the portion of a program where the variable is recognized. Parameters and
variables defined inside a function is not visible from outside. Hence, they have a local scope.
Lifetime of a variable is the period throughout which the variable exits in the memory. The
lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
66
Scripting languages Python Programming
Output
Here, we can see that the value of x is 20 initially. Even though the function my_func()changed
the value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the one
outside. Although they have same names, they are two different variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a global
scope.
We can read these values from inside the function but cannot change (write) them. In order to
modify the value of variables outside the function, they must be declared as global variables
using the keyword global.
Types of Functions
Arguments
In user-defined function topic, we learned about defining a function and calling it. Otherwise, the
function call will result into an error. Here is an example.
def greet(name,msg):
67
Scripting languages Python Programming
Output
Since, we have called this function with two arguments, it runs smoothly and we do not get any
error.
If we call it with different number of arguments, the interpreter will complain. Below is a call to
this function with one and no arguments along with their respective error messages.
Up until now functions had fixed number of arguments. In Python there are other ways to define
a function which can take variable number of arguments.
68
Scripting languages Python Programming
We can provide a default value to an argument by using the assignment operator (=). Here is an
example.
In this function, the parameter name does not have a default value and is required (mandatory)
during a call.
On the other hand, the parameter msg has a default value of "Good morning!". So, it is optional
during a call. If a value is provided, it will overwrite the default value.
Any number of arguments in a function can have a default value. But once we have a default
argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example, if we
had defined the function header above as:
69
Scripting languages Python Programming
When we call a function with some values, these values get assigned to the arguments according
to their position.
For example, in the above function greet(), when we called it as greet("Bruce","How do we do?"), the
value "Bruce" gets assigned to the argument name and similarly "How do we do?" to msg.
Python allows functions to be called using keyword arguments. When we call functions in this
way, the order (position) of the arguments can be changed. Following calls to the above function
are all valid and produce the same result.
As we can see, we can mix positional arguments with keyword arguments during a function call.
But we must keep in mind that keyword arguments must follow positional arguments.
70
Scripting languages Python Programming
Having a positional argument after keyword arguments will result into errors. For example the
function call as follows:
greet(name="Bruce","How do we do?")
Sometimes, we do not know in advance the number of arguments that will be passed into a
function.Python allows us to handle this kind of situation through function calls with arbitrary
number of arguments.
In the function definition we use an asterisk (*) before the parameter name to denote this kind of
argument. Here is an example.
def greet(*names):
print("Hello",name)
greet("Monica","Luke","Steve","John")
71
Scripting languages Python Programming
Output
Hello Monica
Hello Luke
Hello Steve
Hello John
Here, we have called the function with multiple arguments. These arguments get wrapped up into
a tuple before being passed into the function. Inside the function, we use a for loop to retrieve all
the arguments back.
A physical world example would be to place two parallel mirrors facing each other. Any object
in between them would be reflected recursively.
We know that in Python, a function can call other functions. It is even possible for the function
to call itself. These type of construct are termed as recursive functions.
Factorial of a number is the product of all the integers from 1 to that number. For example, the
factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
72
Scripting languages Python Programming
When we call this function with a positive integer, it will recursively call itself by decreasing the
number.
Each function call multiples the number with the factorial of number 1 until the number is equal
to one. This recursive call can be explained in the following steps.
73
Scripting languages Python Programming
Our recursion ends when the number reduces to 1. This is called the base condition.
Every recursive function must have a base condition that stops the recursion or else the function
calls itself infinitely.
Global Variables
In Python, a variable declared outside of the function or in global scope is known as global
variable. This means, global variable can be accessed inside or outside of the function.
x inside : global
x outside: global
In above code, we created x as a global variable and defined a foo() to print the global variable x.
Finally, we call the foo() which will print the value of x.
74
Scripting languages Python Programming
x = "global"
def foo():
x=x*2
print(x)
foo()
The output shows an error because Python treats x as a local variable and x is also not defined
inside foo().
Local Variables
A variable declared inside the function's body or in the local scope is known as local variable.
The output shows an error, because we are trying to access a local variable y in a global scope
whereas the local variable only works inside foo() or local scope.
75
Scripting languages Python Programming
def foo():
y = "local"
print(y)
foo()
local
Let's take a look to the earlier problem where x was a global variable and we wanted to
modify x inside foo().
Here, we will show how to use global variables and local variables in the same code.
76
Scripting languages Python Programming
foo()
global global
local
In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use
multiplication operator * to modify the global variable x and we print both x and y.
After calling the foo(), the value of x becomes global global because we used the x * 2to print two
times global. After that, we print the value of local variable y i.e local.
local x: 10
global x: 5
In above code, we used same name x for both global variable and local variable. We get different
result when we print same variable because the variable is declared in both scopes, i.e. the local
scope inside foo() and global scope outside foo().
77
Scripting languages Python Programming
When we print the variable inside the foo() it outputs local x: 10, this is called local scope of
variable.
Similarly, when we print the variable outside the foo(), it outputs global x: 5, this is called global
scope of variable.
While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword.
Lambda functions can have any number of arguments but only one expression. The expression is
evaluated and returned. Lambda functions can be used wherever function objects are required.
78
Scripting languages Python Programming
print(double(5))
In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is
the expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to the identifier double.
We can now call it as a normal function. The statement
double = lambda x: x * 2
def double(x):
return x * 2
We use lambda functions when we require a nameless function for a short period of time.
The function is called with all the items in the list and a new list is returned which contains items
for which the function evaluats to True.
79
Scripting languages Python Programming
Here is an example use of filter() function to filter out only even numbers from a list.
The function is called with all the items in the list and a new list is returned which contains items
returned by that function for each item.
Here is an example use of map() function to double all the items in a list.
A file containing Python code, for e.g.: example.py, is called a module and its module name would
be example.
80
Scripting languages Python Programming
We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
result = a + b
return result
Here, we have defined a function add() inside a module named example. The function takes in
two numbers and returns their sum.
We can import the definitions inside a module to another module or the interactive interpreter in
Python.
We use the import keyword to do this. To import our previously defined module example we type
the following in the Python prompt.
81
Scripting languages Python Programming
This does not enter the names of the functions defined in example directly in the current symbol
table. It only enters the module name example there.
Using the module name we can access the function using dot (.) operation. For example:
>>> example.add(4,5.5)
9.5
We can check out the full list of Python standard modules and what they are for. These files are
in the Lib directory inside the location where we installed Python.
Standard modules can be imported the same way as we import our user-defined modules.
There are various ways to import modules. They are listed as follows.
We can import a module using import statement and access the definitions inside it using the dot
operator as described above. Here is an example.
82
Scripting languages Python Programming
We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, math.pi is invalid, m.pi is the
correct implementation.
We can import specific names from a module without importing the module as a whole. Here is
an example.
In such case we don't use the dot operator. We could have imported multiple attributes as
follows.
83
Scripting languages Python Programming
We can import all names(definitions) from a module using the following construct.
We imported all the definitions from the math module. This makes all names except those
beginning with an underscore, visible in our scope.
Importing everything with the asterisk (*) symbol is not a good programming practice. This can
lead to duplicate definitions for an identifier. It also hampers the readability of our code.
The Python interpreter has a number of functions that are always available for use. These
functions are called built-in functions. For example, print() function prints the given object to the
standard output device (screen) or to the text stream file.
In Python 3.6 (latest version), there are 68 built-in functions. They are listed below
alphabetically along with brief description.
Method Description
84
Scripting languages Python Programming
Method Description
85
Scripting languages Python Programming
Method Description
86
Scripting languages Python Programming
Method Description
87
Scripting languages Python Programming
Method Description
88
Scripting languages Python Programming
Method Description
89
Scripting languages Python Programming
What is a file?
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.
1. Open a file
2. Read or write (perform operation)
3. Close the 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.
90
Scripting languages Python Programming
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.
Mode Description
Open a file for writing. Creates a new file if it does not exist or truncates the file if it
'w'
exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
Open for appending at the end of the file without truncating it. Creates a new file if it
'a'
does not exist.
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.
91
Scripting languages Python Programming
Unlike other languages, the character 'a' does not imply the number 97 until it is encoded
using ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it is 'cp1252' but 'utf-8' in
Linux.
So, we must not also rely on the default encoding or else our code will behave differently in
different platforms.
Hence, when working with files in text mode, it is highly recommended to specify the encoding
type.
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using
Python 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')
f.close()
92
Scripting languages Python Programming
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.
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised,
causing program flow to stop.
The best way to do this is using the with statement. This ensures that the file is closed when the
block inside with is exited.
In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive
creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All
previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This method
returns the number of characters written to the file.
93
Scripting languages Python Programming
f.write("This file\n\n")
This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is
overwritten.
There are various methods available for this purpose. We can use the read(size) method to read
in size number of data. If size parameter is not specified, it reads and returns up to the end of the
file.
94
Scripting languages Python Programming
We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we get
empty string on further reading.
We can change our current file cursor (position) using the seek() method. Similarly,
the tell() method returns our current position (in number of bytes).
We can read a file line-by-line using a for loop. This is both efficient and fast.
...
This file
Moreover, the print() end parameter to avoid two newlines when printing.
95
Scripting languages Python Programming
Alternately, we can use readline() method to read individual lines of a file. This method reads a
file till the newline, including the newline character.
>>> f.readline()
'This is my first file\n'
>>> f.readline()
'This file\n'
>>> f.readline()
'contains three lines\n'
>>> f.readline()
''
Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
method return empty values when end of file (EOF) is reached.
>>> f.readlines()
There are various methods available with the file object. Some of them have been used in above
examples.
Here is the complete list of methods in text mode with a brief description.
96
Scripting languages Python Programming
Method Description
close() Close an open file. It has no effect if the file is already closed.
detach() Separate the underlying binary buffer from the TextIOBaseand return it.
Read atmost n characters form the file. Reads till end of file if it is
read(n)
negative or None.
Read and return one line from the file. Reads in at most nbytes if
readline(n=-1)
specified.
97
Scripting languages Python Programming
Resize the file stream to size bytes. If size is not specified, resize to
truncate(size=None)
current location.
write(s) Write string s to the file and return the number of characters written.
When writing a program, we, more often than not, will encounter errors.
Error caused by not following the proper structure (syntax) of the language is called syntax error
or parsing error.
>>> if a < 3
File "<interactive input>", line 1
if a < 3
^
SyntaxError: invalid syntax
98
Scripting languages Python Programming
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) etc.
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
>>> open("imaginary.txt")
Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are
raised when corresponding errors occur.
Some of the common built-in exceptions in Python programming along with the error that cause
then are tabulated below.
99
Scripting languages Python Programming
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
100
Scripting languages Python Programming
RuntimeError Raised when an error does not fall under any other category.
101
Scripting languages Python Programming
ValueError Raised when a function gets argument of correct type but improper value.
We can also define our own exception in Python (if required). Visit this page to learn more
about user-defined exceptions.
We can handle these built-in and user-defined exceptions in Python using try, except and finally
statements.
Python has many built-in exceptions which forces our 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.
102
Scripting languages Python Programming
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.
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)
Output
The entry is a
Oops! <class 'ValueError'> occured.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError' > occured.
103
Scripting languages Python Programming
Next entry.
The entry is 2
In this program, we loop until the user enters an integer that has a valid reciprocal. The portion
that can cause exception is placed inside try block.
If no exception occurs, except block is skipped and normal flow continues. But if any exception
occurs, it is caught by the except block.
Here, we print the name of the exception using ex_info() function inside sys module and ask the
user to try again. We can see that the values 'a' and '1.3' causes ValueError and '0' causes
ZeroDivisionError.
In the above example, we did not mention any exception in the except clause.
This is not a good programming practice as it will catch all exceptions and handle every case in
the same way. We can specify which exceptions an except clause will catch.
A try clause can have any number of except clause to handle them differently but only one will
be executed in case an exception occurs.
We can use a tuple of values to specify multiple exceptions in an except clause. Here is an
example pseudo code.
104
Scripting languages Python Programming
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except:
pass
Raising Exceptions
In Python programming, exceptions are raised when corresponding errors occur at run time, but
we can forcefully raise it using the keyword raise.
We can also optionally pass in value to the exception to clarify why that exception was raised.
105
Scripting languages Python Programming
...
MemoryError: This is an argument
>>> try:
... a = int(input("Enter a positive integer: "))
... if a <= 0:
... raise ValueError("That is not a positive number!")
... except ValueError as ve:
... print(ve)
...
Enter a positive integer: -2
That is not a positive number!
try...finally
The try statement in Python can have an optional finally clause. This clause is executed no matter
what, and is generally used to release external resources.
For example, we may be connected to a remote data center through the network or working with
a file or working with a Graphical User Interface (GUI).
In all these circumstances, we must clean up the resource once used, whether it was successful or
not. These actions (closing a file, GUI or disconnecting from network) are performed in the
finally clause to guarantee execution.
try:
f = open("test.txt",encoding = 'utf-8')
finally:
106
Scripting languages Python Programming
f.close()
This type of construct makes sure the file is closed even if an exception occurs.
Python has many built-in exceptions which forces our program to output an error when
something in it goes wrong.
However, sometimes we may need to create custom exceptions that serve our purpose.
In Python, users can define such exceptions by creating a new class. This exception class has to
be derived, either directly or indirectly, from Exception class. Most of the built-in exceptions are
also derived from this class.
Here, we have created a user-defined exception called CustomError which is derived from
the Exception class. This new exception can be raised, like other exceptions, using
the raisestatement with an optional error message.
107
Scripting languages Python Programming
When we are developing a large Python program, it is a good practice to place all the user-
defined exceptions that our program raises in a separate file. Many standard modules do this.
They define their exceptions separately as exceptions.py or errors.py (generally but not always).
User-defined exception class can implement everything a normal class can do, but we generally
make them simple and concise. Most implementations declare a custom base class and derive
others exception classes from this base class. This concept is made clearer in the following
example.
In this example, we will illustrate how user-defined exceptions can be used in a program to raise
and catch errors.
This program will ask the user to enter a number until they guess a stored number correctly. To
help them figure it out, hint is provided whether their guess is greater than or less than the stored
number.
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
108
Scripting languages Python Programming
Enter a number: 12
This value is too large, try again!
Enter a number: 0
This value is too small, try again!
Enter a number: 8
This value is too small, try again!
Enter a number: 10
Congratulations! We guessed it correctly.
109
Scripting languages Python Programming
The other two exceptions (ValueTooSmallError and ValueTooLargeError) that are actually raised by
our program are derived from this class. This is the standard way to define user-defined
exceptions in Python programming, but we are not limited to this way only.
---------------------------------------------------------#####----------------------------------------------------
110