Basic Python

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

Python

(Basic)
Sabyasachi Moitra
[email protected]
OVERVIEW
Introduction
Compiling and Interpreting
First Python Program
Introduction
Developed by Guido van Rossum in the early 1990s.
Features:
• High-level powerful programming language
• Interpreted language
• Object-oriented
• Portable
• Easy to learn & use
• Open source
• Derived from many other programming languages

3
Introduction (2)
Uses:
• Internet Scripting
• Image Processing
• Database Programming
• Artificial Intelligence
…..

4
Compiling and Interpreting
• Many languages compile (translate) the program into a
machine understandable form.

compile execute
----------> ---------->

Source code Intermediate code Output

• Python is directly interpreted into machine instructions.

interpret
---------->

Source code Output


5
Compiling and Interpreting (2)
Compiler Interpreter
Scans the entire program and Translates program one statement at a
translates it as a whole into machine time.
code.
It takes large amount of time to analyze It takes less amount of time to analyze
the source code but the overall the source code but the overall
execution time is comparatively faster. execution time is slower.
Generates intermediate object code No intermediate object code is
which further requires linking, hence generated, hence are memory
requires more memory. efficient.
It generates the error message only Continues translating the program until
after scanning the whole program. the first error is met, in which case it
Hence debugging is comparatively stops. Hence debugging is easy.
hard. 6
Programming language like C, C++ use Programming language like Python,
compilers. Ruby use interpreters.
First Python Program
(Hello.py)

7
Output

8
BASIC SYNTAX
Interactive Mode Programming VS Script Mode Programming
Identifiers
Reserved Words
Lines and Indentation
Some more Basic Syntax
Interactive Mode Programming
VS Script Mode Programming
Interactive Mode Programming Script Mode Programming
Invoking the interpreter without Invoking the interpreter with a script
passing a script file as a parameter parameter, & begins execution of the
brings up the Python prompt. Type a script and continues until the script is
python statement at the prompt and finished. When the script is finished,
press Enter. the interpreter is no longer active
(assuming that user have Python
interpreter set in PATH variable).
C:\Users\moitra>python G:\2.
Python 2.7.13 (v2.7.13:a06454b1afa1, DOCUMENTS\PythonPrograms>pytho
Dec 17 2016, 20:42:59) [MSC v.1500 n test.py
32 bit ( Hello World
Intel)] on win32
Type "help", "copyright", "credits" or
"license" for more information. 10
>>> print("Hello World")
Hello World
Identifiers
• A Python identifier is a name used to identify a variable,
function, class, module or other object.
• An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores
and digits (0 to 9).
• Python does not allow punctuation characters such as @, $,
and % within identifiers.
• Python is a case sensitive programming language.
Manpower and manpower are two different identifiers in
Python.

11
Reserved Words
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
12
and exec not
Lines and Indentation
• Python provides no braces to indicate blocks of code for class
and function definitions or flow control. Blocks of code are
denoted by line indentation.
• The number of spaces in the indentation is variable, but all
statements within the block must be indented the same
amount.
Correct Erroneous
if True: if True:
print "True" print "Answer"
else: print "True"
print "False" else:
print "Answer"
print "False" 13
Basic Syntax (5)
Example
Multi-Line Statements total = item_one + \
item_two + \
item_three
Comments in Python print "Hello World" # comment
Multiple Statements on a Single Line x = 'foo'; print(x + '\n')
…..

14
VARIABLE TYPES
Standard Data Types
Other Operations
Some Type Conversions
Standard Data Types
Standard Data Type Example
counter = 100
Numbers
miles = 1000.0
String name = "John"
List tinylist = [123, 'john']
Tuple tinytuple = (123, 'john')
tinydict = {'name': 'john','code':6734,
Dictionary
'dept': 'sales'}

16
Other Operations
Operation Example
a=b=c=1
Multiple Assignment
a,b,c = 1,2,"john"
Delete del var1[,var2[,var3[....,varN]]]]

Some Type Conversions


Function Description
int(x) Converts x to an integer number
str(x) Converts x to a string representation
list(s) Converts s to a list
tuple(s) Converts s to a tuple 17
dict(d) Creates a dictionary d
…..
BASIC OPERATORS
Types of Operator
Types of Operator
Type Operators
+, -, *, /, %, ** (exponent), // (floor
Arithmetic Operators
division)
Relational Operators ==, !=, >, <, >=, <=
Assignment Operators =, +=, -=, *=, /=, %=, **=, //=
Logical Operators and, or, not
Bitwise Operators &, |, ~, ^, <<, >>
Membership Operators in, not in
Identity Operators is, not is

19
Addition of two nos.
add.py
#addition of two numbers
a=raw_input("Enter 1st no.: ")
b=raw_input("Enter 2nd no.: ")
c=int(a)+int(b)
print('The sum of {0} and {1} is {2}'.format(a, b, c))

Output
G:\2. DOCUMENTS\PythonPrograms>python add.py
Enter 1st no.: 1
Enter 2nd no.: 2
The sum of 1 and 2 is 3
20
DECISION MAKING
Simple if statement
if…else statement
nested if statement
elif Statement
Simple if statement
simple_if.py
#even no. check
a=input("Enter a no: ")
if(a%2==0):
print('{0} is even'.format(a))

Output

if even if not even


G:\2. G:\2.
DOCUMENTS\PythonPrograms DOCUMENTS\PythonPrograms
>python simple_if.py >python simple_if.py
Enter a no: 10 Enter a no: 11
10 is even
22
if…else statement
if_else.py
#even-odd no. check
a=input("Enter a no: ")
if(a%2==0):
print('{0} is even'.format(a))
else:
print('{0} is odd'.format(a))
Output
if even if not even
G:\2. G:\2.
DOCUMENTS\PythonPrograms DOCUMENTS\PythonPrograms
>python if_else.py >python if_else.py
Enter a no: 10 Enter a no: 11
23
10 is even 11 is odd
nested if statement (nested_if.py)

24
Output

25
elif Statement (else_if_ladder.py)

26
Output

27
LOOPING
while Loop
for Loop
nested Loop
while Loop
while_loop.py
i=1
while(i<=5):
print(i)
i=i+1

Output
G:\2. DOCUMENTS\PythonPrograms>python while_loop.py
1
2
3
4 29
5
for Loop
for_loop.py
for i in range(1,6):
print(i)

Output
G:\2. DOCUMENTS\PythonPrograms>python for_loop.py
1
2
3
4
5
30
nested Loops (prime_factor.py)

31
Output

32
PYTHON NUMBERS
Numerical Types
Numeric Functions
Mathematical Constants
Python Numbers (1)
• Python supports four different numerical types:

int long float complex


10 51924361L 15.20 -.6545+26J

• Python also includes some predefined numeric functions:

Type Function Description Example


import math
pow(x, y) The value of print
x**y "math.pow(2, 4)
: ", math.pow(2,
4)
math.pow(2, 4) : 16.0
Mathematical
print "abs(-45)
abs(x) The absolute : ", abs(-45) 34
value of x abs(-45) : 45

…..
Python Numbers (2)
Type Function Description Example
import random
choice(seq) A random item print "choice([1, 2,
from a list, tuple, 3, 5, 9]) : ",
random.choice([1, 2,
or string 3, 5, 9])
choice([1, 2, 3, 5, 9]) : 2

import random
shuffle(lst) Randomizes the list = [20, 16, 10,
Random Number
items of a list in 5];
random.shuffle(list)
place. Returns print "Reshuffled
list : ", list
None
Reshuffled list : [16, 5, 10, 20]

…..

35
Python Numbers (3)
Type Function Description Example
import math
sin (x) Return the sine of print "sin(3) : ",
x radians math.sin(3)
sin(3) : 0.14112000806

import math
Trigonometric cox (x) Return the cosine print “cos(3) : ",
of x radians math.cos(3)
sin(3) : 0.14112000806

…..

36
Python Numbers (4)
• Python also supports two mathematical constants:
pi
e

37
PYTHON STRINGS
Example
Built-in String Methods
Python Strings (1)
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
print "Updated String :- ", str[:6] + 'Python'

Output
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST 39
Updated String :- Hello Python
Python Strings (2)
Python includes some built-in methods to manipulate strings:

String Method Description Example


str = "this str.capitalize() : This
capitalize() Capitalizes first letter of is string is string
string example....wo example....wow!!!
w!!!";
print
"str.capitali
ze() : ",
str.capitaliz
e()
str = "this Length of the
len() Returns the length of the is string string: 32
string example....wo
w!!!";
print "Length
of the
string: ",
len(str)

…..
40
PYTHON LISTS
Example
Basic List Operations
Functions VS Methods
Built-in List Functions
Built-in List Methods
Python Lists (1)
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list # Prints complete list


print list[0] # Prints first element of the list
print list[-1] # Prints last element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

list[0] = 'efgh'; # updating list


print list

del list[2]; # deleting list element


print list 42
Python Lists (2)
Output
['abcd', 786, 2.23, 'john', 70.2]
abcd
70.2
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
['efgh', 786, 2.23, 'john', 70.2]
['efgh', 786, 'john', 70.2]
43
Python Lists (3)
Other Basic List Operations
Expression Result Description
len([1, 2, 3]) 3 Length
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: 123 Iteration
print x,

44
Functions VS Methods
Function Method
A function is a piece of code that is A method is a piece of code that is
called by name. called by name that is associated with
an object.
It can pass data to operate on (i.e., the It is able to operate on data that is
parameters) and can optionally return contained within the class.
data (the return value).
All data that is passed to a function is It is implicitly passed for the object for
explicitly passed. which it was called.
def sum(num1, num2): class Dog:
return num1 + num2 def my_method(self):
print "I am a Dog"
dog = Dog()
dog.my_method() # Prints "I am a
Dog"
45
Python Lists (4)
Some Built-in List Functions
Function Description Example
list = [456, 700, 200]
max(list) Returns item from print "Max value
the list with max element : ", max(list)

value. Max value element : 700

list = [456, 700, 200]


min(list) Returns item from print "Min value
the list with min element : ", min(list)

value. Min value element : 200

…..

46
Python Lists (5)
Some Built-in List Methods
Method Description Example
aList = [123, 'xyz',
list.append(obj) Appends a 'zara', 'abc'];
passed obj into the aList.append( 2009 );
print "Updated List :
existing list. ", aList
Updated List : [123, 'xyz', 'zara',
'abc', 2009]

aList = [123, 'xyz',


list.count(obj) Returns count of 'zara', 'abc', 123];
how many print "Count for 123 :
", aList.count(123)
times obj occurs in print "Count for zara :
", aList.count('zara')
list.
Count for 123 : 2
Count for zara : 1

…..
47
PYTHON TUPLES
Example
Basic Tuple Operations
Built-in Tuple Functions
Lists VS Tuples
Python Tuples (1)
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print tuple # Prints complete tuple


print tuple[0] # Prints first element of the tuple
print tuple[-1] # Prints last element of the tuple
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints tuple two times
print tuple + tinytuple # Prints concatenated tuples

49
Python Tuples (2)
Output
('abcd', 786, 2.23, 'john', 70.2)
abcd
70.2
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

50
Python Tuples (3)
Other Basic Tuple Operations
Expression Result Description
len((1, 2, 3)) 3 Length
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): 123 Iteration
print x,

51
Python Tuples (4)
Some Built-in Tuple Functions
Function Description Example
tuple = (456, 700, 200)
max(tuple) Returns item from print "Max value
the tuple with max element : ", max(tuple)

value. Max value element : 700

tuple = (456, 700, 200)


min(tuple) Returns item from print "Min value
the tuple with min element : ", min(tuple)

value. Min value element : 200

…..

52
Lists VS Tuples
Lists Tuples
Lists are enclosed in brackets ( [ ] ). Tuples are enclosed in parentheses ( ( )
).
Lists' elements and size can be Tuples' elements and size cannot be
changed. changed.
Support item deletion. Doesn't support item deletion.
Example Example
list = [123, 'john'] tuple = (123, 'john')
print list print tuple
del list[1] del tuple[1]
print list print tuple

[123, 'john'] (123, 'john')


[123] Traceback (most recent call last):
File "main.py", line 6, in
del tuple[1]
TypeError: 'tuple' object doesn't support item deletion

53
PYTHON DICTIONARY
Introduction
Example
Properties of Dictionary Keys
Built-in Dictionary Functions
Built-in Dictionary Methods
Python Dictionary (1)
• Python's dictionaries are kind of hash table type.
• They work like associative arrays or hashes found in PHP and
Perl respectively.
• It consists of key-value pairs.
• A dictionary key can be almost any Python type, but are
usually numbers or strings, & values can be any arbitrary
Python object.
• Dictionaries are enclosed by curly braces ({ }) and values can
be assigned and accessed using square braces ([]).

55
Python Dictionary (2)
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734,'dept':'sales'}

print dict['one'] # Prints value for 'one' key


print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

tinydict['name']="Peter" # update existing entry


tinydict['org']="abcd" # Add new entry
print tinydict

del dict[2]; # remove entry with key 2


print "dict: ", dict
dict.clear(); # remove all entries in dict
print "dict: ", dict
del dict ; # delete entire dictionary 56
print "dict: ", dict
Python Dictionary (3)
Output
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
{'dept': 'sales', 'code': 6734, 'name': 'Peter', 'org': 'abcd'}
dict: {'one': 'This is one'}
dict: {}
dict:
57
Properties of Dictionary Keys
• More than one entry per key not allowed, i.e., no duplicate
key is allowed. When duplicate keys encountered during
assignment, the last assignment wins.
• Keys must be immutable. Which means you can use strings,
numbers or tuples as dictionary keys but something like ['key']
is not allowed.

58
Python Dictionary (4)
Some Built-in Dictionary Functions
Function Description Example
dict = {'Name': 'Zara',
len(dict) Gives the total 'Age': 7};
length of the print "Length : %d" %
len (dict)
dictionary. Length : 2

dict = {'Name': 'Zara',


str(dict) Produces a 'Age': 7};
printable string print "Equivalent
String : %s" % str
representation of a (dict)

dictionary. Equivalent String : {'Age': 7,


'Name': 'Zara'}

…..

59
Python Dictionary (5)
Some Built-in Dictionary Methods
Method Description Example
dict = {'Name': 'Zara',
dict.clear() Removes all 'Age': 7};print "Start
elements of Len : %d" % len(dict)
dict.clear()
dictionary dict. print "End Len : %d" %
len(dict)

Start Len : 2
End Len : 0

dict1 = {'Name':
dict.copy() Returns a shallow 'Zara', 'Age': 7};
copy of dict2 = dict1.copy()
print "New Dictinary :
dictionary dict. %s" % str(dict2)

New Dictinary : {'Age': 7, 'Name':


'Zara'}

…..
60
PYTHON DATE & TIME
Some Examples
Python Date & Time (1)
import time; # This is required to include time module.
ticks = time.time() # returns the current system time in ticks
# since 12:00am, January 1, 1970
print "Number of ticks since 12:00am, January 1, 1970:", ticks

Output
Number of ticks since 12:00am, January 1, 1970: 1498320786.91

62
Python Date & Time (2)
import calendar
cal = calendar.month(2017, 6)
print "Here is the calendar:"
print cal

Output
Here is the calendar:
June 2017
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25 63
26 27 28 29 30
PYTHON FUNCTION
What is a Function?
Example
Pass by Reference VS Pass by Value
Types of Function Arguments
The return Statement
Global Variable VS Local Variable
What is a Function?
A function is a block of organized, reusable code that is used to
perform a single, related action.

Syntax
def function_name( parameters ):
#function_body

65
Example
#python function
def test(str):
print (str)

test("Hello World!!!")

Output
Hello World!!!

66
Pass by Reference VS Pass by
Value
Pass by Reference Pass by Value
# Function definition is here # Function definition is here
def changeme( mylist ): def changeme( mylist ):
# This changes a passed list into # This changes a passed list into
this function" this function"
mylist.append([1,2,3,4]); mylist = [1,2,3,4]; # This would
print "Values inside the # assign new reference in mylist
function: ", mylist print "Values inside the
return function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30]; # Now you can call changeme function
changeme( mylist ); mylist = [10,20,30];
print "Values outside the function: changeme( mylist );
", mylist print "Values outside the function:
", mylist
Output
Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Output
Values outside the function: [10, 20, 30, [1, 2, 3, 4]] Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
67
Types of Function Arguments
Function Argument Description Example
def test(str):
Required Arguments The arguments passed to print (str)
a function in correct test()
positional order. The
number of arguments in Traceback (most recent call last):
the function call should File "python_func.py", line 4, in <module>
test()
match exactly with the TypeError: test() takes exactly 1 argument
(0 given)
function definition.
def printinfo( name, age ):
Keyword Arguments When use keyword print "Name: ", name
arguments in a function print "Age ", age

call, the caller identifies printinfo( age=50,


name="miki" )
the arguments by the
Name: miki
parameter name. Thus, Age 50
allowing the arguments
to place in any order. 68
Types of Function Arguments
(2)
Function Argument Description Example
def printinfo( name, age = 35
Default Arguments An argument that ):
assumes a default value print "Name: ", name
print "Age ", age
if a value is not provided
printinfo( age=50,
in the function call for name="miki" )
printinfo( name="miki" )
that argument.
Name: miki
Age 50
Name: miki
Age 35

69
Types of Function Arguments
(3)
Function Argument Description Example
def printinfo( arg1,
Variable-length We may need to process *vartuple ):
Arguments a function for more print "Output is: "
print arg1
arguments than for var in vartuple:
print var
specified while defining
printinfo( 10 )
the function. These printinfo( 70, 60, 50 )
arguments are called Output is:
variable-length 10
Output is:
arguments and are not 70
60
named in the function 50
definition NOTE:
The asterisk (*) placed before the variable
vartuple holds the values of all non-
keyword variable arguments.

70
The return Statement
def add(x,y):
sum=x+y
return sum

total=add(10,20)
print total

Output
30

71
Global Variable VS Local
Variable
total = 0; # This is global variable
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them
total = arg1 + arg2; # Here total is local variable
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total

Output
Inside the function local total : 30
Outside the function global total : 0
72
PYTHON MODULES
What is a Module?
import Statement
from… import Statement
Namespaces and Scoping
Some Functions
Python Packages
What is a Module?
• A module is a file consisting of Python code.
• A module can define functions, classes and variables. It can
also include runnable code.
• A module allows you to logically organize your Python code.
• A module is a Python object with arbitrarily named attributes
that you can bind and reference.

Example
tmodule.py
def print_func( par ):
print "Hello : ", par

74
import Statement
# Import module tmodule
import tmodule

# Now you can call defined function that


# module as follows
tmodule.print_func("Zara")

Output
Hello : Zara

75
from…import Statement
Python's from statement allows you to import specific attributes
from a module into the current namespace.

Syntax Example
from modname import tmodule.py
def print_func( par ):
name1[, name2[, ... print "Hello : ", par

nameN]] def print_func_2(str) :


print "Good Morning
",str
from_import_module.py
from tmodule import print_func_2

print_func_2("Zara")
Output
Good Morning Zara

76
Namespaces and Scoping
• Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects
(values).

• A Python statement can access variables in a local namespace and in the


global namespace. If a local and a global variable have the same name,
the local variable shadows the global variable.

• Each function has its own local namespace.

• Python assumes that any variable assigned a value in a function is local.

• Therefore, in order to assign a value to a global variable within a


function, you must first use the global statement.

• The statement global VarName tells Python that VarName is a global 77


variable. Python stops searching the local namespace for the variable.
Example
Money = 2000 Money = 2000
def AddMoney(): def AddMoney():
# Uncomment the following line # Uncomment the following line
# to fix the code: # to fix the code:
# global Money global Money
Money = Money + 1 Money = Money + 1

print Money print Money


AddMoney() AddMoney()
print Money print Money

Output Output
2000 2000
Traceback (most recent call last): 2001
File "namespace_scoping.py", line 8, in <module>
AddMoney()
File "namespace_scoping.py", line 5, in AddMoney
Money = Money + 1
UnboundLocalError: local variable 'Money' referenced
before assignment
78
Some Functions
Function Description Example
import tmodule
dir( ) Returns a sorted list of
strings containing the print dir(tmodule)

names defined by a Output


['__builtins__', '__doc__', '__file__',
module. '__name__', '__package__', 'print_func',
'print_func_2']
total = 0;
locals() Returns all the names def sum( arg1, arg2 ):
that can be accessed total = arg1 + arg2;
print "locals():
locally from the function, ",locals()
print "globals():
in which its called. ",globals()

globals() Returns all the names sum( 10, 20 );

that can be accessed Output


globally from the locals(): {'arg1': 10, 'arg2': 20, 'total': 30}
globals(): {'__builtins__': <module
function, in which its '__builtin__' (built-in)>, '__file__': 'loc
al_global.py', '__package__': None, 'sum':
called. <function sum at 0x017638F0>, '__name
__': '__main__', 'total': 0, '__doc__': None} 79
…..
Python Packages
A package is a hierarchical file directory structure that defines a
single Python application environment that consists of modules
and subpackages and sub-subpackages, and so on.

G:.
└──phone
__init__.py (required to make Python treat phone as a package)
g3.py
isdn.py
pots.py
80
Example
pots.py
def pots_func():
print "I'm Pots Phone"

isdn.py
def pots_func():
print "I'm ISDN Phone"

g3.py
def pots_func():
print "I'm G3 Phone" 81
Example (contd…)
__init__.py
from pots import pots_func
from isdn import isdn_func
from g3 import g3_func

package.py
import sys

sys.path.append('G:\2. DOCUMENTS\PythonPrograms')

import phone

phone.pots_func()
phone.isdn_func()
phone.g3_func() 82
Output
I'm Pots Phone
I'm ISDN Phone
I'm G3 Phone

83
PYTHON FILE MANAGEMENT
Introduction
Example
Some More File Operation Functions
Introduction
• Until now, we have been reading and writing to the standard
input and output. This works fine as long as the data is small.
• However, many real life problems involve large volumes of
data & in such situations the standard I/O operations poses
two major problems:
- It becomes cumbersome & time consuming to handle large
volumes of data through terminals.
- The entire data is lost either the program is terminated or the
computer is turned off.
• Thus, to have a more flexible approach where data can be
stored on the disks & read whenever necessary without
destroying, the concept of file is employed. 85
Introduction (2)
• Like most other languages, Python supports a number of
functions that have the ability to perform basic file operations:
- Naming a file
- Opening a file (fileobject = open(file_name [, access_mode][, buffering]))
- Reading a file (string = fileobject.read([count]))
- Writing to a file (fileobject.write(string))
- Closing a file (fileobject.close())

access_mode = r, rb, r+, rb+, w, wb, w+, wb+, a, ab,a+, ab+


buffering = <1, 0, >1
count = number of bytes to be read from the opened file
string = content to be written into the opened file 86
Example
# Open a file in write mode
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its
great!!\n");

# Close opened file


fo.close()

# Open the file in read mode


fo = open("foo.txt", "rb")
string = fo.read()
print string

# Close opened file


fo.close() 87
Output
Python is a great language.
Yeah its great!!

88
Some More File Operation
Functions
Function Name Description
tell() Gives the current position within the
file
seek(offset[, from]) Changes the current file position. The
offset argument indicates the number
of bytes to be moved. The from
argument specifies the reference
position from where the bytes are to
be moved.
…..

89
Example (tell())

90
PYTHON EXCEPTION
HANDLING
What is Exception?
Handling an Exception
try.....except.....else
try.....finally
Argument of an Exception
User-Defined Exceptions
What is Exception?
• An exception is an event, which occurs during the execution of
a program that disrupts the normal flow of the program's
instructions.
• When a Python script encounters a situation that it cannot
cope with, it raises an exception.
• An exception is a Python object that represents an error.
• When a Python script raises an exception, it must either
handle the exception immediately otherwise it terminates and
quits.

92
Handling an Exception
• If you have some suspicious code that may raise an exception,
you can defend your program by placing the suspicious code in
a try: block.
• After the try: block, include an except: statement, followed by
a block of code which handles the problem as elegantly as
possible.
• After the except clause(s), you can include an else-clause. The
code in the else-block executes if the code in the try: block
does not raise an exception.

93
try.....except.....else (Syntax)
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
except ExceptionN:
If there is ExceptionN, then execute this block.
else:
If there is no exception then execute this block.
94
try.....except.....else (Example)
Example I Example II
try: try:
fh = open("testfile", "w") fh = open("testfile_2", "r")
fh.write("This is my test file string = fh.read()
for exception handling!!") except IOError:
except IOError: print "Error: can\'t find file
print "Error: can\'t find file or read data"
or read data" else:
else: print string
print "Written content in the fh.close()
file successfully"
fh.close()
Output Output
Written content in the file successfully Error: can't find file or read data

95
try.....finally
• You can use a finally: block along with a try: block.
• The finally block is a place to put any code that must execute, whether the try-block raised
an exception or not.

Syntax
try:
You do your operations here;
......................
[except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
except ExceptionN:
If there is ExceptionN, then execute this block.
else:
If there is no exception then execute this block.]
finally:
This would always be executed. 96
......................
Example
Example I Example II
try: try:
fh = open("testfile", "w") fh = open("testfile_2", "r")
fh.write("This is my test file string = fh.read()
for exception handling!!") except IOError:
except IOError: print "Error: can\'t find file
print "Error: can\'t find file or read data"
or read data" else:
else: print string
print "Written content in the finally:
file successfully" print "Closing the file"
finally: fh.close()
print "Closing the file"
fh.close()
Output Output
Written content in the file successfully Error: can't find file or read data
Closing the file Closing the file

97
Argument of an Exception
• An exception can have an argument, which is a value that
gives additional information about the problem.
• This argument receives the value of the exception mostly
containing the cause of the exception.

Syntax
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
98
Example
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain
numbers\n", Argument

# Call above function here.


temp_convert("xyz");

Output
The argument does not contain numbers
99
invalid literal for int() with base 10: 'xyz'
User-Defined Exceptions
Python also allows you to create your own exceptions by
deriving classes from the standard built-in exceptions.

Example
# user-defined exception
class LevelError(ValueError):
def __init__(self, arg):
self.arg = arg

try:
level=input("Enter level: ")
if(level<1):
# Raise an exception with argument
raise LevelError("Level less than 1")
except LevelError, le:
# Catch exception
print 'Error: ', le.arg
else:
print level
Output
Enter level: 0
Error: Level less than 1 100
References
• Courtesy of YouTube – ProgrammingKnowledge. URL:
https://www.youtube.com/user/ProgrammingKnowledge,
Python Tutorial for Beginners (For Absolute Beginners)
• Courtesy of TutorialsPoint – Python Tutorial. URL:
http://www.tutorialspoint.com/python
• Courtesy of W3Resource – Python Tutorial. URL:
http://www.w3resource.com/python/python-tutorial.php

101

You might also like