Python - UNIT 4 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 110

Scripting languages Python Programming

UNIT 4

Syllabus

 Introduction to Python language


 Environment setup
 Syntax and statements
 Basic operations
 Functions, Built-in-functions and Methods
 Modules
 File I/O
 Exception Handling.

1
Scripting languages Python Programming

Introduction

• Python is a powerful high-level, object-oriented programming language created by Guido


van Rossum.

• It has simple easy-to-use syntax.

• Python is a general-purpose language. It has wide range of applications from Web


development (like: Django and Bottle), scientific and mathematical computing (Orange,
SymPy, NumPy) to desktop graphical user Interfaces (Pygame, Panda3D).

Features of Python Programming

1. A simple language which is easier to learn


Python has a very simple and elegant syntax. It's much easier to read and write
Python programs compared to other languages like: C++, Java, C#. Python makes
programming allows we to focus on the solution rather than syntax.

2. Free and open-source


we can freely use and distribute Python, even for commercial use. Not only can
we use and distribute soft wares written in it, we can even make changes to the Python's
source code.
Python has a large community constantly improving it in each iteration.

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.

4. Extensible and Embeddable


Suppose an application requires high performance. We can easily combine pieces
of C/C++ or other languages with Python code.
This will give our application high performance as well as scripting capabilities
which other languages may not provide out of the box.

5. A high-level, interpreted language


Unlike C/C++, we don't have to worry about daunting tasks like memory

2
Scripting languages Python Programming

management, garbage collection and so on.


Likewise, when we run Python code, it automatically converts our code to the
language our computer understands. We don't need to worry about any lower-level
operations.

6. Large standard libraries to solve common tasks


Python has a number of standard libraries which makes life of a programmer much
easier since we don't have to write all the code our self.

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.

2. Scientific and Numeric Computing

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

3. Creating software Prototypes

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.

4. Good Language to Teach Programming

Python is used by many companies to teach programming to kids and newbies.

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.

There are various ways to start Python.

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

For example: helloWorld.py

To execute this file in script mode we simply write python helloWorld.py at the command
prompt.

3. Integrated Development Environment (IDE)

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

 Keywords are the reserved words in Python.


 We cannot use a keyword as variable name, function name or any other identifier. They
are used to define the syntax and structure of the Python language.
 In Python, keywords are case sensitive.
 There are 33 keywords in Python 3.3. This number can vary slightly in course of time.

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

Keywords in Python programming language

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

Python Identifiers

Identifier is the name given to entities like class, functions, variables etc. in Python. It helps

differentiating one entity from another.

Rules for writing identifiers

1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or


digits (0 to 9) or an underscore (_). Names like myClass, var_1 and print_this_to_screen,
all are valid example.

6
Scripting languages Python Programming

2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.

3. Keywords cannot be used as identifiers.

4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.

5. Identifier can be of any length.

Note:

1. Python is a case-sensitive language.


This means,’Variable’ and ‘variable’ are not the same.
2. Always name identifiers that make sense
While, c = 10 is valid. Writing count = 10 would make more sense and it would be easier
to figure out what it does even when we look at our code after a long gap.
3. Multiple words can be separated using an underscore,
Example: this_is_a_long_variable.
4. We can also use camel-case style of writing, i.e., capitalize every first letter of the word
except the initial word without any spaces. For example: camelCaseExample

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

Incorrect indentation will result into IndentationError.

Python Comments

 Comments are very important while writing a program.


 It describes what's going on inside a program so that a person looking at the source code
does not have a hard time figuring it out. We might forget the key details of the program
we just wrote in a month's time. So taking time to explain these concepts in form of
comments is always fruitful.

 Single-line comments

In Python, we use the hash (#) symbol to start writing a comment.

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 out Hello

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:

#This is a long comment

#and it extends

#to multiple lines

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.

Declaring Variables in Python

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.

Assigning value to a Variable in Python

We can use the assignment operator = to assign the value to a variable.

Example 1: Declaring and assigning a value to a variable

website = "Apple.com"

print(website)

When we run the program, the output will be:

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.

Example 2: Changing value of a variable

website = "Apple.com"
# assigning a new variable to website
website = "Google.com"
print(website)

When we run the program, the output will be:

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.

Example 3: Assigning multiple values to multiple variables

a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)

When we run the program, the output will be:

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)

When we run the program, the output will be:

same
same
same

The second program assigns the same string to all the three variables x, y and z.

Constants

A constant is a type of variable whose value cannot be changed. It is helpful to think of


constants as containers that hold information which cannot be changed later.

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.

Assigning value to a constant in Python

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.

Example 1: Declaring and assigning value to a constant

Create a constant.py

PI = 3.14
GRAVITY = 9.8

Create a main.py

import constant
print(constant.PI)
print(constant.GRAVITY)

When we run the program, the output will be:

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.

Rules and Naming convention for variables and constants

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

3. Use capital letters where possible to declare a constant. For example:

PI
G
MASS
TEMP

4. Never use special symbols like !, @, #, $, %, etc.


5. Don't start name with a digit.
6. Constants are put into Python modules and meant not be changed.
7. Constant and variable names should have combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:

snake_case
MACRO_CASE
camelCase
CapWords

Python Input, Output and Import

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.

Python Output Using print() function

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.

print('This sentence is output to the screen')


# Output: This sentence is output to the screen
a=5
print('The value of a is', a)
# Output: The value of a is 5

The actual syntax of the print() function is

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.

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])

where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')

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')

Traceback (most recent call last):

File "<string>", line 301, in runcode

File "<interactive input>", line 1, in <module>

ValueError: invalid literal for int() with base 10: '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

>>> from math import pi

>>> pi

3.141592653589793

Python Operators

What are operators in python?

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.

Arithmetic operators in Python

Operator Meaning Example

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

* Multiply two operands x*y

/ 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)

Floor division - division that results into whole number


// x // y
adjusted to the left in the number line

x**y (x to the power


** Exponent - left operand raised to the power of right
y)

Example #1: Arithmetic operators in Python

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)

When we run the program, the output will be:

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.

Comparision operators in Python

Operator Meaning Example

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

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal 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

Example #2: Comparison operators in Python

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

Logical operators are and, or, not operators.

Logical operators in Python

Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

Example #3: Logical Operators in Python

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

For example, 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Bitwise operators in Python

Operator Meaning Example

& Bitwise AND x& y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 40 (0010 1000)

Assignment operators

Assignment operators are used in Python to assign values to variables.

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.

Assignment operators in Python

Operator Example Equivatent to

= 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

&= x &= 5 x=x&5

25
Scripting languages Python Programming

|= x |= 5 x=x|5

^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

<<= x <<= 5 x = x << 5

Python Data Types

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))

Integers can be of any length, it is only limited by the memory available.

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)

Notice that the float variable b got truncated.

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 [ ].

>>> a = [1, 2.2, 'python']

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

print("a[2] = ", a[2])


# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])
# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])

Lists are mutable, meaning, value of elements of a list can be altered.

>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]

Split and join methods

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:

# the input is a string


#123
s = input() # s == '1 2 3'
a = s.split() # a == ['1', '2', '3']
print(a)

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.

a = ['red', 'green', 'blue']


print(' '.join(a))
# return red green blue
print(''.join(a))
# return redgreenblue
print('***'.join(a))
# returns red***green***blue

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:

[expression for variable in sequence]

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.

This is how you create a list of n zeros using the generator:

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:

a = [input() for i in range(int(input()))]


print(a)

Slices

With lists and strings, you can do slices. Namely:

A[i:j] slice j-i elements A[i], A[i+1], ..., A[j-1].

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.

Note that A[i] is a list item, not a slice!

Operations on lists

You can easily do many different operations with lists.

x in A Check whether an item in the list. Returns True or False

x not in A The same as not(x in A)

min(A) The smallest element of list

max(A) The largest element in the list

The index of the first occurrence of element x in the list; in its absence generates an
A.index(x)
exception ValueError

A.count(x) The number of occurrences of element x in the list

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.

It is defined within parentheses () where items are separated by commas.

>>> t = (5,'program', 1+3j)

We can use the slicing operator [] to extract items but we cannot change its value.

t = (5,'program', 1+3j)

# t[1] = 'program'

print("t[1] = ", t[1])

# t[0:3] = (5, 'program', (1+3j))

print("t[0:3] = ", t[0:3])

# Generates error

# Tuples are immutable

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 """.

>>> s = "This is a string"

>>> s = '''a multiline

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'

print("s[4] = ", s[4])

# s[6:11] = 'world'

print("s[6:11] = ", s[6:11])

# Generates error

# Strings are immutable in Python

s[5] ='d'

Slices: single character

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.

Number i in S[i] is called an index.

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

Index S[0] S[1] S[2] S[3] S[4]

34
Scripting languages Python Programming

Index S[-5] S[-4] S[-3] S[-2] S[-1]

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.

Slices: immutability of strings

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])

String methods: find() and rfind()

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

as object_name.method_name(arguments). For example, in s.find("e") the string


method find() is applied to the string s with one argument "e".

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.

s = 'my name is bond, james bond, okay?'


print(s.find('bond'))
# 11

37
Scripting languages Python Programming

print(s.find('bond', 12))
# 23

String methods: replace()

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:

print('a bar is a bar, essentially'.replace('bar', 'pub'))


# 'a pub is a pub, essentially'

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.

print('a bar is a bar, essentially'.replace('bar', 'pub', 1))


# 'a pub is a bar, essentially'

String methods: count()

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]

Traceback (most recent call last):

File "<string>", line 301, in runcode

File "<interactive input>", line 1, in <module>

TypeError: 'set' object does not support indexing

39
Scripting languages Python Programming

How to define a set

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.

The order of elements is unimportant. For example, the program

A = {1, 2, 3}
B = {3, 2, 3, 1}
print(A == B)

Print True, because A and B are equal sets.

Each element may enter the set only once. set('Hello') returns the set of four elements: {'H', 'e', 'l',
'o'}.

Operations with elements

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:

primes = {2, 3, 5, 7, 11}


for num in primes:
print(num)

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.

You can transform a set to list using the function list.

Operations on sets

This is how you perform the well-known operations on sets in Python:

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)

A-B Returns the set difference of A and B (the elements


A.difference(B) included in A, but not included in B).

41
Scripting languages Python Programming

A -= B
Removes all elements of B from the set A.
A.difference_update(B)

Returns the symmetric difference of sets A and B (the


A^B
elements belonging to either A or B, but not to both
A.symmetric_difference(B)
sets simultaneously).

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)

A<B Equivalent to A <= B and A != B

A>B Equivalent to A >= B and A != B

Python Dictionary

Dictionary is an unordered collection of key-value pairs.

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

Dictionaries are used in the following cases:

 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:

Capitals = {'Russia': 'Moscow', 'Ukraine': 'Kiev', 'USA': 'Washington'}


Capitals = dict(RA = 'Moscow', Ukraine = 'Kiev', USA = 'Washington')
Capitals = dict([("Russia", "Moscow"), ("Ukraine", "Kiev"), ("USA", "Washington")])
Capitals = dict(zip(["Russia", "Ukraine", "USA"], ["Moscow", "Kiev", "Washington"]))
print(Capitals)

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.

Working with dictionary items

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.

A = {'ab' : 'ba', 'aa' : 'aa', 'bb' : 'bb', 'ba' : 'ab'}


key = 'ac'
if key in A:
del A[key]
try:
del A[key]
except KeyError:
print('There is no element with key "' + key + '" in dict')
print(A)

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)

Conversion between data types

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

Conversion to and from string must contain compatible values.

>>> float('2.5')

2.5

>>> str(25)

'25'

>>> int('1p')

Traceback (most recent call last):

File "<string>", line 301, in runcode

File "<interactive input>", line 1, in <module>

ValueError: invalid literal for int() with base 10: '1p'

We can even convert one sequence to another.

46
Scripting languages Python Programming

>>> set([1,2,3])

{1, 2, 3}

>>> tuple({5,6,7})

(5, 6, 7)

>>> list('hello')

['h', 'e', 'l', 'l', 'o']

To convert to dictionary, each element must be a pair

>>> dict([[1,2],[3,4]])

{1: 2, 3: 4}

>>> dict([(3,26),(4,44)])

{3: 26, 4: 44}

What are if...else statement in Python?

Decision making is required when we want to execute a code only if a certain condition is
satisfied.

The if…elif…else statement is used in Python for decision making.

Python if Statement Syntax

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.

If the text expression is False, the statement(s) is not executed.

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.

# If the number is positive, we print an appropriate message

num = 3

if num > 0:

print(num, "is a positive number.")

print("This is always printed.")

num = -1

if num > 0:

print(num, "is a positive number.")

print("This is also always printed.")

When we run the program, the output will be:

3 is a positive number
This is always printed

48
Scripting languages Python Programming

This is also always printed.

In the above example, num > 0 is the test expression.

The body of if is executed only if this evaluates to True.

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.

Python if...else Statement

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

# Program checks if the number is positive or negative


# And displays an appropriate message
num = 3
# Try these two variations as well.

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.

Python if...elif...else Statement

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.

If all the conditions are False, body of else is executed.

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,

# we check if the number is positive or

# negative or zero and

# display an appropriate message


num = 3.4

# Try these two variations as well:

# num = 0

# num = -4.5

if num > 0:

print("Positive number")

elif num == 0:

print("Zero")

else:

print("Negative number")

When variable num is positive, Positive number is printed.


If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed

Python Flow Control

51
Scripting languages Python Programming

Python Nested if statements

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.

Python Nested if Example

# In this program, we input a number


# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

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

What is for loop in Python?

The for loop in Python is used to iterate over a sequence or other iterable objects. Iterating over a
sequence is called traversal.

Syntax of for Loop

for val in sequence:


Body of for

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.

# Program to find the sum of all numbers stored in a list

# 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)

when we run the program, the output will be:

The sum is 48

The range() function

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: range(0, 10)


print(range(10))

# 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)))

# Output: [2, 5, 8, 11, 14, 17]


print(list(range(2, 20, 3)))

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.

# Program to iterate through a list using indexing

genre = ['pop', 'rock', 'jazz']

# iterate over the list using index

for i in range(len(genre)):

print("I like", genre[i])

When we run the program, the output will be:

I like pop
I like rock
I like jazz

for loop with else

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.

Hence, a for loop's else part runs if no break occurs.

Here is an example to illustrate this.

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")

When we run the program, the output will be:

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.

What is while loop in Python?

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.

Syntax of while Loop in Python

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.

In Python, the body of the while loop is determined through indentation.

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.

Example: Python while Loop


# Program to add natural
# numbers upto
# sum = 1+2+3+...+n
# To take input from the user,
# n = int(input("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum

57
Scripting languages Python Programming

print("The sum is", sum)

When we run the program, the output will be:

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).

Finally the result is displayed.

while loop with else

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.

What is the use of break and continue in Python?

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.

The break and continue statements are used in these cases.

Python break statement

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

# Use of break statement inside loop


for val in "string":
if val == "i":
break
print(val)
print("The end")

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.

Python continue statement

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.

# Program to show the use of continue statement inside loops

for val in "string":

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.

What is pass statement in Python?

In Python programming, pass is a null statement. The difference between


a comment and pass statement in Python is that, while the interpreter ignores a comment
entirely, pass is not ignored.

However, nothing happens when pass is executed. It results into no operation (NOP).

Syntax of pass

pass

We generally use it as a placeholder.

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.

Example: pass Statement

# pass is just a placeholder for


# functionality to be added later.
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass

62
Scripting languages Python Programming

What is a function in Python?

In Python, function is a group of related statements that perform a specific task.

Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.

Furthermore, it avoids repetition and makes code reusable.

Syntax of Function

def function_name(parameters):
"""docstring"""
statement(s)

Above shown is a function definition which consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must
have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

63
Scripting languages Python Programming

Example of a function
def greet(name):

"""This function greets to

the person passed in as

parameter"""

print("Hello, " + name + ". Good morning!")

How to call a function in python?

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.

Although optional, documentation is a good programming practice. Unless we can remember


what we had for dinner last week, always document wer code.

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

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

Here, None is the returned value.

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 and Lifetime of variables

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.

Here is an example to illustrate the scope of a variable inside a function.

def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()

66
Scripting languages Python Programming

print("Value outside function:",x)

Output

Value inside function: 10


Value outside function: 20

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

Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.

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

"""This function greets to


the person with the provided message"""
print("Hello",name + ', ' + msg)
greet("Monica","Good morning!")

Output

Hello Monica, Good morning!

Here, the function greet() has two parameters.

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.

>>> greet("Monica") # only one argument


TypeError: greet() missing 1 required positional argument: 'msg'
>>> greet() # no arguments
TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'

Variable Function Arguments

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.

Three different forms of this type are described below.

68
Scripting languages Python Programming

Python Default Arguments

Function arguments can have default values in Python.

We can provide a default value to an argument by using the assignment operator (=). Here is an
example.

def greet(name, msg = "Good morning!"):


"""
This function greets to
the person with the
provided message.
If message is not provided,
it defaults to "Good
morning!"
"""
print("Hello",name + ', ' + msg)
greet("Kate")
greet("Bruce","How do we do?")

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

def greet(msg = "Good morning!", name):

We would get an error as:

SyntaxError: non-default argument follows default argument

Python Keyword Arguments

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.

>>> # 2 keyword arguments


>>> greet(name = "Bruce",msg = "How do we do?")

>>> # 2 keyword arguments (out of order)


>>> greet(msg = "How do we do?",name = "Bruce")

>>> # 1 positional, 1 keyword argument


>>> greet("Bruce",msg = "How do we do?")

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?")

Will result into error as:

SyntaxError: non-keyword arg after keyword arg

Python Arbitrary Arguments

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):

"""This function greets all

the person in the names tuple."""

# names is a tuple with arguments

for name in 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.

What is recursion in Python?

Recursion is the process of defining something in terms of itself.

A physical world example would be to place two parallel mirrors facing each other. Any object
in between them would be reflected recursively.

Python Recursive Function

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.

Following is an example of recursive function to find the factorial of an integer.

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

Example of recursive function


# An example of a recursive function to
# find the factorial of a number
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
num = 4
print("The factorial of", num, "is", calc_factorial(num))

In the above example, calc_factorial() is a recursive functions as it calls itself.

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.

calc_factorial(4) # 1st call with 4


4 * calc_factorial(3) # 2nd call with 3
4 * 3 * calc_factorial(2) # 3rd call with 2
4 * 3 * 2 * calc_factorial(1) # 4th call with 1
4*3*2*1 # return from 4th call as number=1
4*3*2 # return from 3rd call
4*6 # return from 2nd call
24 # return from 1st call

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.

Python Global and Local Variables

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.

Let's see an example on how a global variable is created in Python.

Example 1: Create a Global Variable


x = "global"
def foo():
print("x inside :", x)
foo()
print("x outside:", x)

When we run the code, the will output be:

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.

What if we want to change value of x inside a function?

74
Scripting languages Python Programming

x = "global"
def foo():
x=x*2
print(x)
foo()

When we run the code, the will output be:

UnboundLocalError: local variable 'x' referenced before assignment

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.

Example 2: Accessing local variable outside the scope


def foo():
y = "local"
foo()
print(y)

When we run the code, the will output be:

NameError: name 'y' is not defined

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

Let's see an example on how a local variable is created in Python.

Example 3: Create a Local Variable

Normally, we declare a variable inside the function to create a local variable.

def foo():
y = "local"
print(y)
foo()

When we run the code, it will output:

local

Let's take a look to the earlier problem where x was a global variable and we wanted to
modify x inside foo().

Global and local variables

Here, we will show how to use global variables and local variables in the same code.

Example 4: Using Global and Local variables in same code


x = "global"
def foo():
global x
y = "local"
x=x*2
print(x)
print(y)

76
Scripting languages Python Programming

foo()

When we run the code, the will output be:

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.

Example 5: Global variable and Local variable with same name


x=5
def foo():
x = 10
print("local x:", x)
foo()
print("global x:", x)

When we run the code, the will output be:

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.

What are lambda functions in Python?

In Python, anonymous function is a function that is defined without a name.

While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword.

Hence, anonymous functions are also called lambda functions.

How to use lambda Functions in Python?

A lambda function in python has the following syntax.

Syntax of Lambda Function in python

lambda arguments: expression

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.

Example of Lambda Function in python

Here is an example of lambda function that doubles the input value.


# Program to show the use of lambda functions
double = lambda x: x * 2
# Output: 10

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

is nearly the same as

def double(x):

return x * 2

Use of Lambda Function in python

We use lambda functions when we require a nameless function for a short period of time.

In Python, we generally use it as an argument to a higher-order function (a function that takes in


other functions as arguments). Lambda functions are used along with built-in functions
like filter(), map() etc.

Example use with filter()

The filter() function in Python takes in a function and a list as arguments.

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.

# Program to filter out only the even items from a list


my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
# Output: [4, 6, 8, 12]
print(new_list)

Example use with map()

The map() function in Python takes in a function and 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.

# Program to double each item in a list using map()


my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
# Output: [2, 10, 8, 12, 16, 22, 6, 24]
print(new_list)

What are modules in Python?

Modules refer to a file containing Python statements and definitions.

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.

Let us create a module. Type the following and save it as example.py.

# Python Module example

def add(a, b):


"""This program adds two
numbers and return the result"""

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.

How to import modules in Python?

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.

>>> import example

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

Python has a ton of standard modules available.

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.

Python import statement

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.

# import statement example


# to import standard module math
import math
print("The value of pi is", math.pi)

When we run the program, the output will be:

The value of pi is 3.141592653589793

82
Scripting languages Python Programming

Import with renaming

We can import a module by renaming it as follows.

# import module by renaming it


import math as m
print("The value of pi is", m.pi)

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.

Python from...import statement

We can import specific names from a module without importing the module as a whole. Here is
an example.

# import only pi from math module


from math import pi
print("The value of pi is", pi)

We imported only the attribute pi from the module.

In such case we don't use the dot operator. We could have imported multiple attributes as
follows.

>>> from math import pi, e


>>> pi
3.141592653589793
>>> e
2.718281828459045

83
Scripting languages Python Programming

Import all names

We can import all names(definitions) from a module using the following construct.

# import all names from the standard module math


from math import *
print("The value of pi is", pi)

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.

Python built in functions

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

Python abs() returns absolute value of a number

Python all() returns true when all elements in iterable is true

Python any() Checks if any Element of an Iterable is True

84
Scripting languages Python Programming

Method Description

Python ascii() Returns String Containing Printable Representation

Python bin() converts integer to binary string

Python bool() Coverts a Value to Boolean

Python bytearray() returns array of given byte size

Python bytes() returns immutable bytes object

Python callable() Checks if the Object is Callable

Python chr() Returns a Character (a string) from an Integer

Python classmethod() returns class method for given function

Python compile() Returns a Python code object

Python complex() Creates a Complex Number

Python delattr() Deletes Attribute From the Object

Python dict() Creates a Dictionary

Python dir() Tries to Return Attributes of Object

85
Scripting languages Python Programming

Method Description

Python divmod() Returns a Tuple of Quotient and Remainder

Python enumerate() Returns an Enumerate Object

Python eval() Runs Python Code Within Program

Python exec() Executes Dynamically Created Program

Python filter() constructs iterator from elements which are true

Python float() returns floating point number from number, string

Python format() returns formatted representation of a value

Python frozenset() returns immutable frozenset object

Python getattr() returns value of named attribute of an object

Python globals() returns dictionary of current global symbol table

Python hasattr() returns whether object has named attribute

Python hash() returns hash value of an object

Python help() Invokes the built-in Help System

86
Scripting languages Python Programming

Method Description

Python hex() Converts to Integer to Hexadecimal

Python id() Returns Identify of an Object

Python input() reads and returns a line of string

Python int() returns integer from a number or string

Python isinstance() Checks if a Object is an Instance of Class

Python issubclass() Checks if a Object is Subclass of a Class

Python iter() returns iterator for an object

Python len() Returns Length of an Object

Python list() Function creates list in Python

Python locals() returns dictionary of current local symbol table

Python map() Applies Function and Returns a List

Python max() returns largest element

Python memoryview() returns memory view of an argument

87
Scripting languages Python Programming

Method Description

Python min() returns smallest element

Python next() Retrieves Next Element from Iterator

Python object() Creates a Featureless Object

Python oct() converts integer to octal

Python open() Returns a File object

Python ord() returns Unicode code point for Unicode character

Python pow() returns x to the power of y

Python print() Prints the Given Object

Python property() returns a property attribute

Python range() return sequence of integers between start and stop

Python repr() returns printable representation of an object

Python reversed() returns reversed iterator of a sequence

Python round() rounds a floating point number to ndigits places.

88
Scripting languages Python Programming

Method Description

Python set() returns a Python set

Python setattr() sets value of an attribute of object

Python slice() creates a slice object specified by range()

Python sorted() returns sorted list from a given iterable

Python staticmethod() creates static method from a function

Python str() returns informal representation of an object

Python sum() Add items of an Iterable

Python super() Allow we to Refer Parent Class by super

Python tuple() Function Creates a Tuple

Python type() Returns Type of an Object

Python vars() Returns __dict__ attribute of a class

Python zip() Returns an Iterator of Tuples

Python __import__() Advanced Function Called by import

89
Scripting languages Python Programming

Python File I/O

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.

Hence, in Python, a file operation takes place in the following order.

1. Open a file
2. Read or write (perform operation)
3. Close the file

How to open 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

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.

Python File Modes

Mode Description

'r' Open a file for reading. (default)

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.

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)

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

f = 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

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.

f = open("test.txt",mode = 'r',encoding = 'utf-8')

How to close a file Using Python?

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')

# perform file operations

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.

A safer way is to use a try...finally block.

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.

We don't need to explicitly call the close() method. It is done internally.

with open("test.txt",encoding = 'utf-8') as f:

# perform file operations

How to write to File Using Python?

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

with open("test.txt",'w',encoding = 'utf-8') as f:

f.write("my first file\n")

f.write("This file\n\n")

f.write("contains three lines\n")

This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is
overwritten.

We must include the newline characters ourselves to distinguish different lines.

How to read files in Python?

To read a file in Python, we must open the file in reading mode.

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.

>>> f = open("test.txt",'r',encoding = 'utf-8')


>>> f.read(4) # read the first 4 data
'This'

>>> f.read(4) # read the next 4 data


' is '

>>> f.read() # read in the rest till end of file


'my first file\nThis file\ncontains three lines\n'

>>> f.read() # further reading returns empty sting


''

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).

>>> f.tell() # get the current file position


56

>>> f.seek(0) # bring file cursor to initial position


0

>>> print(f.read()) # read the entire file


This is my first file
This file
contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.

>>> for line in f:

... print(line, end = '')

...

This is my first file

This file

contains three lines

The lines in file itself has a newline character '\n'.

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()

['This is my first file\n', 'This file\n', 'contains three lines\n']

Python File Methods

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

Python File Methods

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.

fileno() Return an integer number (file descriptor) of the file.

flush() Flush the write buffer of the file stream.

isatty() Return True if the file stream is interactive.

Read atmost n characters form the file. Reads till end of file if it is
read(n)
negative or None.

readable() Returns True if the file stream can be read from.

Read and return one line from the file. Reads in at most nbytes if
readline(n=-1)
specified.

Read and return a list of lines from the file. Reads in at


readlines(n=-1)
most n bytes/characters if specified.

Change the file position to offset bytes, in reference to from (start,


seek(offset,from=SEEK_SET)
current, end).

97
Scripting languages Python Programming

seekable() Returns True if the file stream supports random access.

tell() Returns the current file location.

Resize the file stream to size bytes. If size is not specified, resize to
truncate(size=None)
current location.

writable() Returns True if the file stream can be written to.

write(s) Write string s to the file and return the number of characters written.

writelines(lines) Write a list of lines to the file.

Python Errors and Built-in Exceptions

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

We can notice here that a colon is missing in the if statement.

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

Traceback (most recent call last):

File "<string>", line 301, in runcode

File "<interactive input>", line 1, in <module>

ZeroDivisionError: division by zero

>>> open("imaginary.txt")

Traceback (most recent call last):

File "<string>", line 301, in runcode

File "<interactive input>", line 1, in <module>

FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'

Python Built-in Exceptions

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

Python Built-in Exceptions

Exception Cause of Error

AssertionError Raised when assert statement fails.

AttributeError Raised when attribute assignment or reference fails.

EOFError Raised when the input() functions hits end-of-file condition.

FloatingPointError Raised when a floating point operation fails.

GeneratorExit Raise when a generator's close() method is called.

ImportError Raised when the imported module is not found.

IndexError Raised when index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).

MemoryError Raised when an operation runs out of memory.

NameError Raised when a variable is not found in local or global scope.

NotImplementedError Raised by abstract methods.

100
Scripting languages Python Programming

OSError Raised when system operation causes system related error.

OverflowError Raised when result of an arithmetic operation is too large to be represented.

Raised when a weak reference proxy is used to access a garbage collected


ReferenceError
referent.

RuntimeError Raised when an error does not fall under any other category.

Raised by next() function to indicate that there is no further item to be returned


StopIteration
by iterator.

SyntaxError Raised by parser when syntax error is encountered.

IndentationError Raised when there is incorrect indentation.

TabError Raised when indentation consists of inconsistent tabs and spaces.

SystemError Raised when interpreter detects internal error.

SystemExit Raised by sys.exit() function.

TypeError Raised when a function or operation is applied to an object of incorrect type.

Raised when a reference is made to a local variable in a function or method, but


UnboundLocalError
no value has been bound to that variable.

UnicodeError Raised when a Unicode-related encoding or decoding error occurs.

101
Scripting languages Python Programming

UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.

UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.

UnicodeTranslateError Raised when a Unicode-related error occurs during translating.

ValueError Raised when a function gets argument of correct type but improper value.

ZeroDivisionError Raised when second operand of division or modulo operation is zero.

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 Exception Handling- Try, Except and Finally

What are exceptions in Python?

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

Catching Exceptions in Python

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.
# 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

The reciprocal of 2 is 0.5

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.

Catching Specific Exceptions in Python

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 (TypeError, ZeroDivisionError):


# handle multiple exceptions
# TypeError and ZeroDivisionError
pass

except:

# handle all other exceptions

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.

>>> raise KeyboardInterrupt


Traceback (most recent call last):
...
KeyboardInterrupt

>>> raise MemoryError("This is an argument")


Traceback (most recent call last):

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.

Here is an example of file operations to illustrate this.

try:

f = open("test.txt",encoding = 'utf-8')

# perform file operations

finally:

106
Scripting languages Python Programming

f.close()

This type of construct makes sure the file is closed even if an exception occurs.

Python Custom Exceptions

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.

>>> class CustomError(Exception):


... pass
...

>>> raise CustomError


Traceback (most recent call last):
...
__main__.CustomError

>>> raise CustomError("An error occurred")


Traceback (most recent call last):
...
__main__.CustomError: An error occurred

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.

Example: User-Defined Exception in Python

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.

# define Python user-defined exceptions


class Error(Exception):
"""Base class for other exceptions"""
Pass

class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass

# our main program

108
Scripting languages Python Programming

# user guesses a number until he/she gets it right


# we need to guess this number
number = 10
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()

print("Congratulations! We guessed it correctly.")

Here is a sample run of this program.

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

Here, we have defined a base class called Error.

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

You might also like