Sie sind auf Seite 1von 372

Python Introduction

Features
 Simple and Easy to Learn
 Freeware and Open Source
 Platform Independent (Behaves)
 Portability
 Dynamically Typed Language (Variant)
 Procedural, OOP, Modualar, Script
 Interpreted
 Extensible
 Embed
 Extensible Library
Different flavors of Python

 Cpython – Standard
 Jython –Run on Java Platform
 IronPython- C# .Net
 RubyPython- Ruby
 Pypy- Python interpreter and just-in-time
compiler
 Stackless Python - Multithread , Concurrency
and Parallel
 Pythonxy -scientific and engineering
 Anaconda Python: distribution for large-
scale data processing, predictive analytics, and
scientific computing
Identifier and Reserved Word
 Identifier
◦ Alphanumeric and _
◦ Should not start with a digit
◦ Case sensitive
 Reserved Word -33
◦ import keyword
◦ keyword.kwlist
Data Type
 Dynamically typed programming language
 Datatype are not explicit declared
 Fundamental datatype
◦ int
◦ float
◦ complex
◦ bool
◦ str
Integer and Float
 long v2
◦ Decimal
◦ Binary
◦ Octal
◦ Hexadecimal
 Base Conversion
 Float – Floating point number – Decimal
◦ Exponential form
Complex and Boolean
 a+b j
 Arithmetic Operation
 Boolean
◦ True - 1
◦ False - 0
Numeric Expressions
>>> jj = 23 Operatio
>>> xx = 2 Operator
>>> kk = jj % 5 n
>>> xx = xx + 2 >>> print kk
>>> print xx + Addition
3
4 >>> print 4 ** 3 Subtracti
>>> yy = 440 * 12 -
64 on
>>> print yy Multiplica
5280 *
tion
>>> zz = yy / 1000
>>> print zz / Division
5
** Power
5 23 Remaind
20 %
er

3
Order of Evaluation

 When we string operators together -


Python must know which one to do first
 This is called “operator precedence”
 Which operator “takes precedence” over
the others

x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
• Highest precedence rule to lowest
precedence rule
• Parenthesis are always respected
• Exponentiation (raise to a power)
• Multiplication, Division, and Remainder
• Addition and Subtraction Parenthesis
Power
• Left to right Multiplication
Addition
Left to Right
Division
 10/2
 9/2
 9//2
Mathematical Functions:
Function Returns ( description )
abs(x) The absolute value of x: the (positive) distance between x and zero.
ceil(x) The ceiling of x: the smallest integer not less than x
cmp(x, y) -1 if x < y, 0 if x == y, or 1 if x > y
x
exp(x) The exponential of x: e
fabs(x) The absolute value of x.
floor(x) The floor of x: the largest integer not greater than x
log(x) The natural logarithm of x, for x> 0
log10(x) The base-10 logarithm of x for x> 0 .
max(x1, x2,...) The largest of its arguments: the value closest to positive infinity
min(x1, x2,...) The smallest of its arguments: the value closest to negative infinity
modf(x) The fractional and integer parts of x in a two-item tuple. Both parts
have the same sign as x. The integer part is returned as a float.
pow(x, y) The value of x**y.
round(x [,n]) x rounded to n digits from the decimal point. Python rounds away from
zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
sqrt(x) The square root of x for x > 0
Random Number Functions:
Function Returns ( description )
choice(seq) A random item from a list, tuple, or string.
randrange ([start,] A randomly selected element from range(start, stop,
stop [,step]) step)
random() A random float r, such that 0 is less than or equal to
r and r is less than 1
seed([x]) Sets the integer starting value used in generating
random numbers. Call this function before calling
any other random module function. Returns None.
shuffle(lst) Randomizes the items of a list in place. Returns
None.
uniform(x, y) A random float r, such that x is less than or equal to
r and r is less than y
Trigonometric Functions:
Function Description
acos(x) Return the arc cosine of x, in radians.
asin(x) Return the arc sine of x, in radians.
atan(x) Return the arc tangent of x, in radians.
atan2(y, x) Return atan(y / x), in radians.
cos(x) Return the cosine of x radians.
hypot(x, y) Return the Euclidean norm, sqrt(x*x + y*y).
sin(x) Return the sine of x radians.
tan(x) Return the tangent of x radians.
degrees(x) Converts angle x from radians to degrees.
radians(x) Converts angle x from degrees to radians.
Mathematical Constants:
Constant Description
pi The mathematical constant pi.
e The mathematical constant e.
Strings - Unicode
 can create them simply by enclosing characters in quotes.
 Python treats single quotes the same as double quotes.
 Creating strings is as simple as assigning a value to a variable. For
example:
var1 = 'Hello World!'
var2 = "Python Programming"
Accessing Values in Strings:
 Python does not support a character type; these are treated as strings of length
one, thus also considered a substring.
 Example:
var 1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]

This will produce following result:


var1[0]: H
Looking Inside Strings

• We can get at any


m a r k e t
single character in a
0 1 2 3 4 5
string using an index
specified in square
brackets
• The index value must
be an integer and
starts at zero
quote
 Single quote-’
 Double quote-”
 Triple quote-’’’/”””
◦ Multiple lines
◦ To include ‘ and “ simultaneously
◦ To define doc stream
 Negative index
Substring/slice operator
 S[begin : end]
 Begin to end-1index
 S[3:8]
 S[ : ]
 S[3: ]
 S[ : ]
operator
 +-concatenation
◦ S=“iiit”+20
 *-string repetation
◦ S=“iiit”*5
Built-in String Methods:
1 capitalize()
Capitalizes first letter of string
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width
columns
3 count(str, beg= 0,end=len(string))
Counts how many times str occurs in string, or in a substring of string if starting index
beg and ending index end are given
3 decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the
default string encoding.
4 encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a ValueError
unless errors is given with 'ignore' or 'replace'.
5 endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end
are given) ends with suffix; Returns true if so, and false otherwise
6 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not
provided
7 find(str, beg=0 end=len(string))

Determine if str occurs in string, or in a substring of string if starting index beg and
ending index end are given; returns index if found and -1 otherwise
8 index(str, beg=0, end=len(string))

Same as find(), but raises an exception if str not found

9 isa1num()

Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise
10 isalpha()

Returns true if string has at least 1 character and all characters are alphabetic and
false otherwise
11 isdigit()

Returns true if string contains only digits and false otherwise

12 islower()

Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise
13 isnumeric()

Returns true if a unicode string contains only numeric characters and false otherwise

14 isspace()

Returns true if string contains only whitespace characters and false otherwise
15 istitle()
Returns true if string is properly "titlecased" and false otherwise
16 isupper()
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise
17 join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a
string, with separator string
18 len(string)
Returns the length of the string
19 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width
columns
20 lower()
Converts all uppercase letters in string to lowercase
21 lstrip()
Removes all leading whitespace in string
22 maketrans()
Returns a translation table to be used in translate function.
23 max(str)
Returns the max alphabetical character from the string str
24 min(str)

Returns the min alphabetical character from the string str

25 replace(old, new [, max])

Replaces all occurrences of old in string with new, or at most max occurrences if max
given
26 rfind(str, beg=0,end=len(string))

Same as find(), but search backwards in string

27 rindex( str, beg=0, end=len(string))

Same as index(), but search backwards in string

28 rjust(width,[, fillchar])

Returns a space-padded string with the original string right-justified to a total of


width columns.
29 rstrip()

Removes all trailing whitespace of string

30 split(str="", num=string.count(str))

Splits string according to delimiter str (space if not provided) and returns list of
substrings; split into at most num substrings if given
31 splitlines( num=string.count('\n'))

Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs
removed
32 startswith(str, beg=0,end=len(string))

Determines if string or a substring of string (if starting index beg and ending index
end are given) starts with substring str; Returns true if so, and false otherwise
33 strip([chars])

Performs both lstrip() and rstrip() on string

34 swapcase()

Inverts case for all letters in string

35 title()

Returns "titlecased" version of string, that is, all words begin with uppercase, and the
rest are lowercase
36 translate(table, deletechars="")

Translates string according to translation table str(256 chars), removing those in the
del string
37 upper()

Converts lowercase letters in string to uppercase

38 zfill (width)

Returns original string leftpadded with zeros to a total of width characters; intended
for numbers, zfill() retains any sign given (less one zero)
39 isdecimal()

Returns true if a unicode string contains only decimal characters and false otherwise
Type conversion
 Type casting
 Type coercion
 Int( )
 Float( )
 Complex( )
 Bool( )
 Str( )
Immutable
 All fundamental data types are immutable.
 a=10
 type a
 id (a)
 Object reusability
◦ Memory utilization is high
◦ Performance utilization increases
List
 Collection of related data
◦ Order is important/preserved
◦ Duplication allowed
◦ []
◦ Heterogeneous data types are allowed
◦ Mutable
Tuple
 Immutable
Set
 All distinct element
 Order not required
 Function
◦ Add( )
◦ Remove( )
◦ S={ } ******
 Empty set
Frozen set
 Immutable

S={10,20}
Fs=frozenset(s)
Dictionary
 Mutable
 Key value pair
 d={k1:v1,k2:v2,k3:v3}
 Duplicate key X
 Value Duplicate are allowed
Range
 range(n)
 range(begin,end) end-1
 range(begin, end, increment/decrement)
 Immutable
Bytes(0-255)
 L=[10,15,20]
 B=bytes(f)
 Immutable
Byte Array
 Mutable
None
 Return Type
 Point into null value
 How many none?
Escape Character
 Same as C
Comments
 Single
 Multiple
input() function
 2.x
◦ raw_input() / input ()
◦ n=int(raw_input()) # Type casting
◦ n=input() # No type casting is required
 3.x
◦ input () # Return type is str
 Write a program to add two number
x=int(input("Enter first number : ")
y=int(input("Enter second number : ")
print("Sum is : " x+y)
multiple value input
n1,n2= [int(n) for n in input ("Enter two
Numbers ").split()]
print (n1+n2)
Write a program to input student
information and display the value
student_id
Student_name
student_cgpa
student_backlog (True / False )

student_id = input("Enter Student id : ")


student_name = input("Enter Student Name : ")
student_cgpa = float(input("Enter Student CGPA : "))
student_backlog = bool (input("Is Student having backlog [True/False] : ")

print ("Student id : ", student_id)


print ("Student name : ", student_name)
print ("Student id : ", student_cgpa)
print ("Student Backlog : ", student_backlog)
eval(n) # Typecasting x
n=eval(input("Any data as per requirment "))
# Evaluate any expression
Command Line Argument

class A{
public static void main(String args[]){

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}

java A sonoo jaiswal 1 3 abc

Output: sonoo
jaiswal
1
3
abc
#include <stdio.h>

int main( int argc, char *argv[] ) {

printf("Program name %s\n", argv[0]);

if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}

./a.out argument
Write a program to add numbers . Numbersare given as
command line arguments

list of string

from sys import argv


l=argv[1:]
sum=0
for n in l:
sum = sum + int(n)
print ("Additon of numbers ", sum)

Pcmd.py
Simulate cp command
from sys import argv
s=open( argv[1])
d=open(argv[2],'w')
for line in s :
d.write(line)

Separator Default - Blank

Cp.py
""
Python - Basic Operators
Python language supports following type of operators.
 Arithmetic Operators
 Comparision Operators
 Logical (or Relational) Operators
 Assignment Operators
 Conditional (or ternary) Operators
Python Arithmetic Operators:
Operator Description Example
+ Addition - Adds values on either side of the a + b will give 30
operator
- Subtraction - Subtracts right hand operand a - b will give -10
from left hand operand
* Multiplication - Multiplies values on either a * b will give 200
side of the operator
/ Division - Divides left hand operand by b / a will give 2
right hand operand
% Modulus - Divides left hand operand by b % a will give 0
right hand operand and returns remainder
** Exponent - Performs exponential (power) a**b will give 10 to
calculation on operators the power 20
// Floor Division - The division of operands 9//2 is equal to 4 and
where the result is the quotient in which 9.0//2.0 is equal to 4.0
the digits after the decimal point are
removed.
Python Comparison
Operators:
Operato
Description Example
r
== Checks if the value of two operands are equal or not, if (a == b) is not true.
yes then condition becomes true.
!= Checks if the value of two operands are equal or not, if (a != b) is true.
values are not equal then condition becomes true.
<> Checks if the value of two operands are equal or not, if (a <> b) is true. This is
values are not equal then condition becomes true. similar to != operator.
> Checks if the value of left operand is greater than the (a > b) is not true.
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the (a < b) is true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand is less than or equal (a <= b) is true.
to the value of right operand, if yes then condition
becomes true.
Python Assignment Operators:
Operator Description Example
= Simple assignment operator, Assigns values from right c = a + b will
side operands to left side operand assigne value of a +
b into c
+= Add AND assignment operator, It adds right operand to c += a is equivalent
the left operand and assign the result to left operand to c = c + a
-= Subtract AND assignment operator, It subtracts right c -= a is equivalent
operand from the left operand and assign the result to left to c = c - a
operand
*= Multiply AND assignment operator, It multiplies right c *= a is equivalent
operand with the left operand and assign the result to left to c = c * a
operand
/= Divide AND assignment operator, It divides left operand c /= a is equivalent
with the right operand and assign the result to left to c = c / a
operand
%= Modulus AND assignment operator, It takes modulus c %= a is equivalent
using two operands and assign the result to left operand to c = c % a
**= Exponent AND assignment operator, Performs exponential c **= a is
(power) calculation on operators and assign value to the equivalent to c = c
left operand ** a
//= Floor Division and assigns a value, Performs floor division c //= a is equivalent
on operators and assign value to the left operand to c = c // a
Python Bitwise Operators:
Operat
Description Example
or
& Binary AND Operator copies a bit to the (a & b) will give 12
result if it exists in both operands. which is 0000 1100
| Binary OR Operator copies a bit if it exists (a | b) will give 61
in either operand. which is 0011 1101
^ Binary XOR Operator copies the bit if it is (a ^ b) will give 49
set in one operand but not both. which is 0011 0001
~ Binary Ones Complement Operator is unary (~a ) will give -60
and has the effect of 'flipping' bits. which is 1100 0011
<< Binary Left Shift Operator. The left a << 2 will give 240
operands value is moved left by the which is 1111 0000
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left a >> 2 will give 15
operands value is moved right by the which is 0000 1111
number of bits specified by the right
operand.

A=60 b=13
Python Logical Operators:
Operat
Description Example
or
and Called Logical AND operator. If both the (a and b) is true.
operands are true then then condition
becomes true.
or Called Logical OR Operator. If any of the two (a or b) is true.
operands are non zero then then condition
becomes true.
not Called Logical NOT Operator. Use to not(a and b) is false.
reverses the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.
Python Membership
Operators:
In addition to the operators discussed previously, Python has membership
operators, which test for membership in a sequence, such as strings, lists,
or tuples.

Operator Description Example

in Evaluates to true if it finds a variable in the x in y, here in results in a


specified sequence and false otherwise. 1 if x is a member of
sequence y.

not in Evaluates to true if it does not finds a x not in y, here not in


variable in the specified sequence and false results in a 1 if x is a
otherwise. member of sequence y.
Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
~+- Ccomplement, unary plus and minus (method names for
the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += Assignment operators
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators
print()

print(string)
print() #No argument printf("\n")
print(10*"X")
sep - attribute

a,b,c=10,20,30
print(a,b,c) # 10 20 30 default separator -
blank
print(a,b,c,sep=':')
end - attribute

print('iiit')
print('bhubaneswar')

print('iiit', end='') # by default end is \n


print('bhubaneswar')
Replacement - {}

name = 'iiit'
place='Bhubaneswar'

print('Welcome to {} {}'.format(name,place))
print('Welcome to {0} {1}'.format(name,place))
print('Welcome to {n}
{p}'.format(n=name,p=place))
formatted string

%i %d - Signed decimal value


%f %s - string and other object

name = 'abc'
marks= [60,70,80]
cgpa=7.544
print (' %s has got %s and cgpa is %.1f'
%(name,marks,cgpa))
Flow Control
 Selection
◦ If
◦ If-else
◦ If-elif-else
◦ If-elif
 Iterative / repetitive statement
◦ For
◦ While
 Transfer Statement
◦ Break
◦ Continue
◦ Pass
Indentation
No {}
Example
largest among 3 nos.
even or odd
Number to digit
for iterator_var in sequence:
statements(s)

for i in range(1, 5):


for j in range(i):
print(i, end=' ')
print()
continue
break
pass
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.
Suppose we have a loop or a function or
class that is not implemented yet, but we
want to implement it in the future. They
cannot have an empty body.
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass

def function(args):
pass

Pass.py
Input Name and print initial
Write a program to find value of sin(X)

Forex.py
Sin.py
The while Loop: a Condition-
Controlled Loop
 while loop: while condition is true, do
something
◦ Two parts:
 Condition tested for true or false value
 Statements repeated as long as condition is true
◦ In flow chart, line goes back to previous part
◦ General format:
while condition:
statements
GCD of Two number

Gcd.py
Array
Lists and arrays are used in Python to store
data(any data type- strings, integers etc),
both can be indexed and iterated also.
Difference between lists and arrays are the
functions that we can perform on them.
divide an
Array – Homogenous
List – Heterogeneous

import array as arr


a = arr.array('i',list )
Insertion sort

Insertion.py
Function
def name(arg1, arg2, ...):
"""documentation"“ # optional doc string
statements

return # from procedure


return expression # from function
Types of Argument

Required Arguments
Number of arguments should be same in
both function call and function def
Order/position should be same

Gcd of two number


GCD of two number
def gcd (m,n):
while m!=n:
if m>n :
m=m-n
else:
n=n-m
return m
a= int(input ('Enter first number : '))
b= int (input ('Enter second number : ') )
g=gcd(a,b)
print(g)
GCD of ten number
Gcd5.py
Keyword Arguments
Order/position is not required
initialization will be done based on
keyword(name)

def display(a,b):
print(a,b)
print (b=20,a=10)
Key.py
Default argument
 No of arguments need not be same in
function call and function definition
 Some of argument will be consider as
default argument
def hello_func(gretting,name='you'):
return '{},{}'.format(greeting,name)

print(hello_func('Hi','IIIT'))
print(hello_func('Hi'))
Variable length argument
 Variable length argument
 In function definition argument preceded
with * or ** (As per requirement)

Variable.py
Args.py
Recursive Function
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)

a=int(input("Enter first number:"))


b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
Input ten number and print in reverse
order without using any sequence

Reverse.py
Local Scope and Global Scope
 When Python encounters a variable, it
◦ first checks to see if the variable is defined in
the local scope
◦ then checks to see if the variable is defined in
the global scope

But: try to avoid this feature.


Keep global variables global, and local variables local
N=20
Def f1():
n=50
print (n)
Def f2():
print (n)
F1()
F2()
Global.py
def f1():

n=50
print (n)
def f2():
print (n)
f1()
f2()
A variable can be declared in one of two ways…

When it is accessible from all


When it is accessible ONLY
parts of a program
within a function/procedure.
(ie. Anywhere!)

A GLOBAL Variable. A LOCAL Variable.


Result ?

36

Result ?

NameError: name
'fixed_number' is
not defined
Look carefully at this code…

This simply asks the user for a number and then calls a
function to increment each time the CheckGuess function is
called.

Type this into Python & see what happens


Look carefully at this code…

Insert global guesses

Note the use of the keyword global. This allows functio to


modify/change the value of the global variable guesses!
Functions are first-class objects
Functions can be used as any other datatype, eg:
◦ Arguments to function
◦ Return values of functions
◦ Assigned to variables
◦ Parts of tuples, lists, etc
>>> def square(x): return x*x
>>> def applier(q, x): return
q(x)
>>> applier(square, 7)
49
Applier.py
def cube(n)
return n*n*n

f=lambda n: n*n*n

lambda input_arguments: expression

print ( f(5))
Any number of argument but only one
expression
def square_cube (x):
def square(x):
return x*x
def cube (x):
return x*x*x
return [square(x),cube(x)]

print(square_cube(3))

Sq_cube.py
Modify using lambda function
def square_cube (x):
square = lambda x: x*x
cube = lambda x:x*x*x
return [square(x),cube(x)]

print(square_cube(3))

sq_cube_lambda.py
Write a Lambda function to add two
number
f=lambda n,m:n+m
a=int(input('Enter 1st number '))
b=int(input('Enter 2nd number '))
print(f(a,b))

add_lambda.py
Higher-Order Functions
• A higher-order function is a function that takes another function as a
parameter
• They are “higher-order” because it’s a function of a function
• Examples
– Map
– Reduce
– Filter
• Lambda works great as a parameter to higher-order functions if you can
deal with its limitations
Write a program to find square of each element in a list

def sqr(n):
return n*n
l=[2,4,5,6]
for num in l:
print (sqr(num))
Map
map(function, iterable, ...)

• Map applies function to each element of


iterable and creates a list of the results
• We can optionally provide more iterables as
parameters to map and it will place tuples in
the result list
• Map returns an iterator which can be cast to
list
def sqr(n):
return n*n
l=[2,4,5,6]
list1=list(map(sqr,l))
print(list1)
l=[2,4,5,6]
list1=list/tuple/set etc(map(lambda
x:x*x,l))
print(list1)
Multiply two list using map function
 l1-=[2,4,6]
 L2=[4,7,8]
 L3=[8,28,48]
l1=[2,4,6]
l2=[4,6,8]
l3=tuple(map(lambda x,y:x*y,l1,l2))
print(l3)
l=['1','4','5']
print(l)
convert into integer list

Map2.py
l=['1','4','5']
print(l)
l1=list(map(int,l))
print(l1)
Filter
filter(function, iterable)
• The filter runs through each element of iterable
(any iterable object such as a List or another
collection)
• It applies function to each element of iterable
• If function returns True for that element then the
element is put into a List
• This list is returned from filter in versions of python
under 3
• In python 3, filter returns an iterator which must be
cast to type list with list()
 Given a list of numbers, find all
numbers divisible by 13.
 Input : my_list = [12, 65, 54, 39, 102, 339,
221, 50, 70]
 Output : [65, 39, 221]
my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70, ]
result = list(filter(lambda x: (x % 13 == 0),
my_list))
print(result)

Filter1.py
Given a list of strings, find all
palindromes.
Y="".join(reversed(x))
my_list = []
for word in range(5):
my_list.append(input("Enter word : "))

result = list(filter(lambda x: (x ==
"".join(reversed(x))), my_list))

print(result)

filter2.py
Intersection of two array
arr1 = [1, 3, 4, 5, 7]
arr2 = [2, 3, 5, 6]
result = list(filter(lambda x: x in arr1, arr2))
print ("Intersection : ",result)
Largest element in an array
import array as arr
a = arr.array('i', )
for i in range(5):
a.append(int(input()))
print (a)

l=a[0]
for i in range(1, len(a)):
if l<a[i] :
l=a[i]
print (l)
reduce(function,
Reduce
iterable[,initializer])

• Reduce will apply function to each element in iterable along with the
sum so far and create a cumulative sum of the results
• function must take two parameters
• If initializer is provided, initializer will stand as the first argument in the
sum
• in python 3 reduce() requires an import statement
• from functools import reduce
from functools import reduce
import array as arr
l = arr.array('i', )
for i in range(5):
l.append(int(input('Enter number : ')))
print (l)
print(reduce(lambda a,b : a if a > b else b,l))
Factorial of a number
from functools import reduce
n=int(input('Enter a number: '))
print(reduce(lambda
x,y:x*y,range(1,n+1),1))
Find the even number , then find largest among them
from functools import reduce
c = reduce(lambda a,b : a if a > b else b,filter(lambda x: (x%2 ==0), (1,2,3,4)))
print(c)
Reduce Problem
Goal: given a list of numbers I want to find the
average of those numbers in a few lines using
reduce()

For Loop Method:


- sum up every element of the list
- divide the sum by the length of the list
Reduce Problem
from functools import reduce
nums = [92, 27, 63, 43, 88, 8, 38, 91, 47, 74, 18, 16,
29, 21, 60, 27, 62, 59, 86, 56]

avg = reduce(lambda x, y : x + y, nums) / len(nums)


print(avg)

Reduce1.py
MapReduce

Problem: Given an email how do you tell if it is


spam?

- Count occurrences of certain words. If


they occur too frequently the email is
spam.
The String Data Type

 Text is represented in programs by the


string data type.
 A string is a sequence of characters
enclosed within quotation marks (") or
apostrophes (').

Python Programming, 2/e 131


The String Data Type
 We can access the individual characters in
a string through indexing.
 The positions in a string are numbered
from the left, starting with 0.
 The general form is <string>[<expr>],
where the value of expr determines
which character is selected from the
string.

Python Programming, 2/e 132


The String Data Type

H e l l o B o b

0 1 2 3 4 5 6 7 8
>>> greet = "Hello Bob"
>>> greet[0]
'H'
>>> print(greet[0], greet[2], greet[4])
Hlo
>>> x = 8
>>> print(greet[x - 2])
B

Python Programming, 2/e 133


The String Data Type
H e l l o B o b
0 1 2 3 4 5 6 7 8
 In a string of n characters, the last character is at
position n-1 since we start counting with 0.
 We can index from the right side using negative
indexes.
>>> greet[-1]
'b'
>>> greet[-3]
'B'

Python Programming, 2/e 134


The String Data Type
 Indexing returns a string containing a
single character from a larger string.
 We can also access a contiguous
sequence of characters, called a substring,
through a process called slicing.

Python Programming, 2/e 135


The String Data Type
 Slicing:
<string>[<start>:<end>]
 start and end should both be ints
 The slice contains the substring beginning
at position start and runs up to but
doesn’t include the position end.

Python Programming, 2/e 136


The String Data Type
H e l l o B o b

0 1 2 3 4 5 6 7 8
>>> greet[0:3]
'Hel'
>>> greet[5:9]
' Bob'
>>> greet[:5]
'Hello'
>>> greet[5:]
' Bob'
>>> greet[:]
'Hello Bob'

Python Programming, 2/e 137


The String Data Type
 If either expression is missing, then the
start or the end of the string are used.
 Can we put two strings together into a
longer string?
 Concatenation “glues” two strings
together (+)
 Repetition builds up a string by multiple
concatenations of a string with itself (*)

Python Programming, 2/e 138


The String Data Type
 The function len will return the length of a
string.
>>> "spam" + "eggs"
'spameggs'
>>> "Spam" + "And" + "Eggs"
'SpamAndEggs'
>>> 3 * "spam"
'spamspamspam'
>>> "spam" * 5
'spamspamspamspamspam'
>>> (3 * "spam") + ("eggs" * 5)
'spamspamspameggseggseggseggseggs'

Python Programming, 2/e 139


The String Data Type
>>> len("spam")
4
>>> for ch in "Spam!":
print (ch, end=" ")

Spam!

Python Programming, 2/e 140


The String Data Type

Operator Meaning
+ Concatenation
* Repetition
<string>[] Indexing
<string>[:] Slicing
len(<string>) Length
for <var> in <string> Iteration through characters

Python Programming, 2/e 141


Strings, Lists, and Sequences
 It turns out that strings are really a special kind of
sequence, so these operations also apply to
sequences!
>>> [1,2] + [3,4]
[1, 2, 3, 4]
>>> [1,2]*3
[1, 2, 1, 2, 1, 2]
>>> grades = ['A', 'B', 'C', 'D', 'F']
>>> grades[0]
'A'
>>> grades[2:4]
['C', 'D']
>>> len(grades)
5

Python Programming, 2/e 142


Strings, Lists, and Sequences
 Strings are always sequences of
characters, but lists can be sequences of
arbitrary values.
 Lists can have numbers, strings, or both!

myList = [1, "Spam ", 4, "U"]

Python Programming, 2/e 143


Strings, Lists, and Sequences
 We can make a list of months:

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"]

 To get the months out of the sequence,


do this:
monthAbbrev = months[n-1]

Python Programming, 2/e 144


Strings, Lists, and Sequences
# month2.py
# A program to print the month name, given it's number.
# This version uses a list as a lookup table.

def main():

# months is a list used as a lookup table


months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

n = eval(input("Enter a month number (1-12): "))

print ("The month abbreviation is", months[n-1] + ".")

main()

 Note that the months line overlaps a line.


Python knows that the expression isn’t
complete until the closing ] is encountered.

Python Programming, 2/e 145


Strings, Lists, and Sequences
# month2.py
# A program to print the month name, given it's number.
# This version uses a list as a lookup table.

def main():

# months is a list used as a lookup table


months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

n = eval(input("Enter a month number (1-12): "))

print ("The month abbreviation is", months[n-1] + ".")

main()

 Since the list is indexed starting from 0, the n-1


calculation is straight-forward enough to put in
the print statement without needing a separate
step.

Python Programming, 2/e 146


Strings, Lists, and Sequences
 This version of the program is easy to
extend to print out the whole month
name rather than an abbreviation!
months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]

Python Programming, 2/e 147


Strings, Lists, and Sequences
 Lists are mutable, meaning they can be changed.
Strings can not be changed.
>>> myList = [34, 26, 15, 10]
>>> myList[2]
15
>>> myList[2] = 0
>>> myList
[34, 26, 0, 10]
>>> myString = "Hello World"
>>> myString[2]
'l'
>>> myString[2] = "p"

Traceback (most recent call last):


File "<pyshell#16>", line 1, in -toplevel-
myString[2] = "p"
TypeError: object doesn't support item assignment

Python Programming, 2/e 148


Strings and Character Numbers
 The ord function returns the numeric (ordinal)
code of a single character.
 The chr function converts a numeric code to
the corresponding character.
>>> ord("A")
65
>>> ord("a")
97
>>> chr(97)
'a'
>>> chr(65)
'A'

Python Programming, 2/e 149


Other String Methods
 There are a number of other string
methods. Try them all!
◦ s.capitalize() – Copy of s with only the first
character capitalized
◦ s.title() – Copy of s; first character of each
word capitalized
◦ s.center(width) – Center s in a field of given
width

Python Programming, 2/e 150


Other String Operations
◦ s.count(sub) – Count the number of
occurrences of sub in s
◦ s.find(sub) – Find the first position where sub
occurs in s
◦ s.join(list) – Concatenate list of strings into
one large string using s as separator.
◦ s.ljust(width) – Like center, but s is left-
justified

Python Programming, 2/e 151


Other String Operations
◦ s.lower() – Copy of s in all lowercase letters
◦ s.lstrip() – Copy of s with leading whitespace
removed
◦ s.replace(oldsub, newsub) – Replace
occurrences of oldsub in s with newsub
◦ s.rfind(sub) – Like find, but returns the right-
most position
◦ s.rjust(width) – Like center, but s is right-
justified

Python Programming, 2/e 152


Other String Operations
◦ s.rstrip() – Copy of s with trailing whitespace
removed
◦ s.split() – Split s into a list of substrings
◦ s.upper() – Copy of s; all characters converted
to uppercase

Python Programming, 2/e 153


Input/Output as String Manipulation
 Often we will need to do some string
operations to prepare our string data for
output (“pretty it up”)
 Let’s say we want to enter a date in the
format “05/24/2003” and output “May 24,
2003.” How could we do that?

Python Programming, 2/e 154


Input/Output as String Manipulation
 Input the date in mm/dd/yyyy format (dateStr)
 Split dateStr into month, day, and year strings
 Convert the month string into a month number
 Use the month number to lookup the month name
 Create a new date string in the form “Month Day,
Year”
 Output the new date string

Python Programming, 2/e 155


Input/Output as String Manipulation
 The first two lines are easily
implemented!
dateStr = input("Enter a date (mm/dd/yyyy): ")
monthStr, dayStr, yearStr = dateStr.split("/")
 The date is input as a string, and then
“unpacked” into the three variables by
splitting it at the slashes and using
simultaneous assignment.

Python Programming, 2/e 156


Input/Output as String Manipulation
 Next step: Convert monthStr into a
number
 We can use the int function on monthStr
to convert "05", for example, into the
integer 5. (int("05") = 5)

Python Programming, 2/e 157


Input/Output as String Manipulation

 Note: eval would work, but for the leading 0


>>> int("05")
5
>>> eval("05")
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
eval("05")
File "<string>", line 1
05
^
SyntaxError: invalid token

 This is historical baggage. A leading 0 used to be


used for base 8 (octal) literals in Python.
Python Programming, 2/e 158
Input/Output as String Manipulation
months = [“January”, “February”, …, “December”]
monthStr = months[int(monthStr) – 1]
 Remember that since we start counting at
0, we need to subtract one from the
month.
 Now let’s concatenate the output string
together!

Python Programming, 2/e 159


Input/Output as String Manipulation
print ("The converted date is:", monthStr, dayStr+",", yearStr)

 Notice how the comma is appended to


dayStr with concatenation!
 >>> main()
Enter a date (mm/dd/yyyy): 01/23/2010
The converted date is: January 23, 2010

Python Programming, 2/e 160


Input/Output as String Manipulation
 Sometimes we want to convert a number into a
string.
 We can use the str function.
>>> str(500)
'500'
>>> value = 3.14
>>> str(value)
'3.14'
>>> print("The value is", str(value) + ".")
The value is 3.14.

Python Programming, 2/e 161


Input/Output as String Manipulation
 If value is a string, we can concatenate a
period onto the end of it.
 If value is an int, what happens?
>>> value = 3.14
>>> print("The value is", value + ".")
The value is

Traceback (most recent call last):


File "<pyshell#10>", line 1, in -toplevel-
print "The value is", value + "."
TypeError: unsupported operand type(s) for +: 'float' and 'str'

Python Programming, 2/e 162


Input/Output as String Manipulation
 We now have a complete set of type
conversion operations:

Function Meaning
float(<expr>) Convert expr to a floating point value

int(<expr>) Convert expr to an integer value

str(<expr>) Return a string representation of expr

eval(<string>) Evaluate string as an expression

Python Programming, 2/e 163


String Formatting
 String formatting is an easy way to get
beautiful output!
Change Counter

Please enter the count of each coin type.


Quarters: 6
Dimes: 0
Nickels: 0
Pennies: 0

The total value of your change is 1.5

 Shouldn’t that be more like $1.50??

Python Programming, 2/e 164


String Formatting
 We can format our output by modifying
the print statement as follows:
print("The total value of your change is ${0:0.2f}".format(total))

 Now we get something like:


The total value of your change is $1.50

 Key is the string format method.

Python Programming, 2/e 165


String Formatting
 <template-string>.format(<values>)
 {} within the template-string mark “slots”
into which the values are inserted.
 Each slot has description that includes
format specifier telling Python how the
value for the slot should appear.

Python Programming, 2/e 166


String Formatting
print("The total value of your change is ${0:0.2f}".format(total)

 The template contains a single slot with


the description: 0:0.2f
 Form of description:
<index>:<format-specifier>
 Index tells which parameter to insert into
the slot. In this case, total.

Python Programming, 2/e 167


String Formatting
 The formatting specifier has the form:
<width>.<precision><type>
 f means "fixed point" number
 <width> tells us how many spaces to use
to display the value. 0 means to use as
much space as necessary.
 <precision> is the number of decimal
places.

Python Programming, 2/e 168


String Formatting
>>> "Hello {0} {1}, you may have won ${2}" .format("Mr.", "Smith", 10000)
'Hello Mr. Smith, you may have won $10000'

>>> 'This int, {0:5}, was placed in a field of width 5'.format(7)


'This int, 7, was placed in a field of width 5'

>>> 'This int, {0:10}, was placed in a field of witdh 10'.format(10)


'This int, 10, was placed in a field of witdh 10'

>>> 'This float, {0:10.5}, has width 10 and precision 5.'.format(3.1415926)


'This float, 3.1416, has width 10 and precision 5.'

>>> 'This float, {0:10.5f}, is fixed at 5 decimal places.'.format(3.1415926)


'This float, 3.14159, has width 0 and precision 5.'

Python Programming, 2/e 169


String Formatting
 If the width is wider than needed, numeric
values are right-justified and strings are left-
justified, by default.
 You can also specify a justification before the
width.
>>> "left justification: {0:<5}.format("Hi!")
'left justification: Hi! '
>>> "right justification: {0:>5}.format("Hi!")
'right justification: Hi!'
>>> "centered: {0:^5}".format("Hi!")
'centered: Hi! '

Python Programming, 2/e 170


Using in as an Operator

 The in keyword can


also be used to >>> fruit = 'banana’
check to see if one >>> 'n' in fruit
True
string is "in" another >>> 'm' in fruit
string False
>>> 'nan' in fruit
 The in expression is True
a logical expression >>> if 'a' in fruit :
and returns True or ... print 'Found it!’
False and can be ...
Found it!
used in an if >>>
statement
String Comparison

if word == 'banana':
print 'All right, bananas.'

if word < 'banana':


print 'Your word,' + word + ', comes before banana.’
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.’
else:
print 'All right, bananas.'
>>> stuff = 'Hello world’
>>> type(stuff)<type 'str'>
>>> dir(stuff)
['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']

http://docs.python.org/lib/string-methods.html
Searching a
String
 We use the find() b a n a n a
function to search for
a substring within 0 1 2 3 4 5
another string
 find() finds the first >>> fruit = 'banana'
occurance of the >>> pos = fruit.find('na')
substring >>> print pos
2
 If the substring is not >>> aa = fruit.find('z')
found, find() returns - >>> print aa
1 -1
 Remember that string
position starts at zero
Making everything UPPER CASE

 You can make a copy of a


string in lower case or >>> greet = 'Hello Bob'
>>> nnn = greet.upper()
upper case >>> print nnn
 Often when we are HELLO BOB
>>> www = greet.lower()
searching for a string >>> print www
using find() - we first hello bob
>>>
convert the string to
lower case so we can
search a string regardless
of case
Search and Replace

 The replace()
function is like a
“search and >>> greet = 'Hello Bob'
replace” >>> nstr = greet.replace('Bob','Jane')
operation in a >>> print nstr
word processor Hello Jane
>>> nstr = greet.replace('o','X')
 It replaces all >>> print nstrHellX BXb
occurrences of >>>
the search string
with the
replacement
string
Stripping Whitespace

 Sometimes we want
to take a string and >>> greet = ' Hello Bob '
remove whitespace at >>> greet.lstrip()
'Hello Bob '
the beginning and/or >>> greet.rstrip()
end ' Hello Bob'
>>> greet.strip()
 lstrip() and rstrip() to 'Hello Bob'
the left and right only >>>
 strip() Removes both
begin and ending
whitespace
Prefixes

>>> line = 'Please have a nice day’


>>> line.startswith('Please')
True
>>> line.startswith('p')
False
Write a program for testing SPAM mail
from collections import Counter

data_set = ''' IIIT Bhubaneswar owes its origins to the initiative of the Government Odisha. It is a result of the desire of the Government to establish a world class institute of
Information Technology in the state. The Institute has been registered as a society in Nov 2006. In January 2014, the Institute is converted to a University by the
Government of Odisha.

There is misconception that IIIT Bhubaneswar is a Institute promoted in PPP mode by the Government. The Institute is fully owned by the Government of Odisha. The
Information Technology Department is the controlling Department. The Government provides funds for the Infrastructure creation. However, the Institute has to earn
its Revenue Expenditure. This is the model in all State Government promoted IIITs in Bangalore, Hyderabad and Delhi. The Institute enjoys academic, financial and
administrative autonomy by the powers invested through the IIIT Bhubaneswar act. IIIT aspires to be a national Institute in line with its Peer Institutes.

The Governance structure of the Institute is modelled after those of the IITs. The Governor of the state is the Chancellor of the Institute. The Board of Governors has
members from Odisha Legislative Assembly, Government of Odisha, Leaders from the IT industry and Eminent educationists. Currently, the Chairman of the Institute is
the Chief Secretary of the Government of Odisha. The Director is the Executive Head of the Institute. The Director is assisted by the Registrar, the Deans, the
Controller of examinations and the Comptroller of finance in day-to-day management of the Institute

The Institute has its focus on quality and rigorous education, quality resource, academic infrastructure, technology and innovation. These initiatives have helped IIIT-
Bhubaneswar achieve pre-eminence in India and beyond.

'''
split_it = data_set.split()

Counter = Counter(split_it)

most_occur = Counter.most_common(10)

print(most_occur)
Program for converting string to list
def Convert(string):
li = list(string.split(" "))
return li
str1 = "This is an example"
print(Convert(str1))
Writing for anargrams

''' Input : s1 = "listen"


s2 = "silent"
Output : The strings are anagrams.

Input : s1 = "dad"
s2 = "bad"
Output : The strings aren't anagrams.
'''
def check(s1, s2):
if (sorted(s1) == sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")

s1 = input('Enter first string ')


s2 = input('Enter second string ')
check(s1, s2)
Count no of vowels ‘frequency’ in a string
def Check_Vow(string, vowels):
final = [x for x in string if x in vowels]
print(len(final))
print(final)

string = "This is an example"


vowels = "AeEeIiOoUu"
Check_Vow(string, vowels);
''' Primary conditions for password validation :

Minimum 8 characters.
The alphabets must be between [a-z]
At least one alphabet should be of Upper
Case [A-Z]
At least 1 number or digit between [0-9].
At least 1 character from [ _ or @ or $ ].
'''
import re

password = input ('Enter password : ')


flag = 0
while True:
if (len(password) < 8):
flag = -1
break
elif not re.search("[a-z]", password):
flag = -1
break
elif not re.search("[A-Z]", password):
flag = -1
break
elif not re.search("[0-9]", password):
flag = -1
break
elif not re.search("[_@$]", password):
flag = -1
break
elif re.search("\s", password):
flag = -1
break
else:
flag = 0
print("Valid Password")
break

if flag == -1:
print("Not a Valid Password")
 Files are bytes on disk. Two types, text and
binary (we are working with text)
 open creates a connection between the
disk contents and the program
The current file position
 Every file maintains a current file
position.
 It is the current position in the file, and
indicates what the file will read next
Remember the file object buffer
 When the disk file is opened, the
contents of the file are copied into the
buffer of the file object
 The current position is the present index
in that list

fp=open (filename,mode)
A list of the different modes of opening a file:

Modes Description

r Opens a file for reading only. The file pointer is placed at the beginning
of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed
at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer will be at the
beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file
pointer will be at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the
file exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading
and writing.
A list of the different modes of opening a file:
wb+ Opens a file for both writing and reading in binary format. Overwrites
the existing file if the file exists. If the file does not exist, creates a new
file for reading and writing.

a Opens a file for appending. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.

ab Opens a file for appending in binary format. The file pointer is at the end
of the file if the file exists. That is, the file is in the append mode. If the
file does not exist, it creates a new file for writing.

a+ Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing.

ab+ Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for reading
and writing.

x exclusive
>>> f = open("hours.txt")
>>> f.read()
'123 Susan 12.5 8.1 7.6 3.2\n
456 Brad 4.0 11.6 6.5 2.7 12\n Reading Files
789 Jenn 8.0 8.0 8.0 8.0 7.5\n'

name = open("filename")
◦ opens the given file for reading, and returns a
file object
name.read() - file's entire contents as a
string
name.read(n) - read n characters
name.readline() - next line from file
as a string
name.readlines() - file's contents as a
list of lines
◦ the lines from a file object can also be read
using a for loop
File Input Template
 A template for reading files in Python:
name = open("filename")
for line in name:
statements

>>> input = open("hours.txt")


>>> for line in input:
... print(line.strip()) # strip() removes \n

123 Susan 12.5 8.1 7.6 3.2


456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5
The file object atrributes:
Once a file is opened and you have one file object, you can get various information
related to that file.
Here is a list of all attributes related to file object:

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.readable Returns true if file readable, false otherwise.
File.writeable Returns true if file writeable, false otherwise.
 Example:
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace

 This would produce following result:


Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0
Writing Files:
The file object provides a set of access methods to make our lives easier. We would
see how to use read() and write() methods to read and write files.
The write() Method:
 The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.
 The write() method does not add a newline character ('\n') to the end of the
string:
Syntax:
fileObject.write(string);
 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.
Example:
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\r\nYeah its
great!!\r\n");
fo.close()

The above method would create foo.txt file and would write given content in that
file and finally it would close that file. If you would open this file, it would have
following content
Python is a great language.
Yeah its great!!
The close() Method:
The close() method of a file object flushes any unwritten information and
closes the file object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method
to close a file.
 Syntax:
fileObject.close();
Example:
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
fo.close()
 This would produce following result:
Name of the file: foo.txt
with statement
open and close occur in pairs (or
should) so Python provides a shortcut, the
with statement
 creates a context that includes an exit
which is invoked automatically
 for files, the exit is to close the file
with expression as variable:
suite
File is closed automatically when
the suite ends
the tell() method
 The tell() method tells you the
current file position
 The positions are in bytes (think
characters for UTF-8) from the beginning
of the file
my_file.tell() => 42L
the seek() method
 the seek() method updates the
current file position to a new file index (in
bytes offset from the beginning of the file)
 fd.seek(0) # to the beginning of the
file
 fd.seek(100) # 100 bytes from beginning
counting bytes is a pain
 counting bytes is a pain
 seek has an optional argument set:
◦ 0: count from the beginning
◦ 1: count for the current file position
◦ 2: count from the end (backwards)
Exercise
 Write a function input_stats that
accepts a file name as a parameter and
that reports the longest line in the file.
◦ example input file, carroll.txt:
Beware the Jabberwock, my son,
the jaws that bite, the claws that catch,
Beware the JubJub bird and shun
the frumious bandersnatch.
>>> input_stats("carroll.txt")
longest line = 42 characters
◦ expected
the jaws that bite,output:
the claws that catch,
Exercise Solution
def input_stats(filename):
input = open(filename)
longest = ""
for line in input:
if len(line) > len(longest):
longest = line

print("Longest line =", len(longest))


print(longest)
Exercise
 Suppose we have this hours.txt data:
123 Suzy 9.5 8.1 7.6 3.1 3.2
456 Brad 7.0 9.6 6.5 4.9 8.8
789 Jenn 8.0 8.0 8.0 8.0 7.5

 Compute each worker's total hours and


hours/day.
◦ Assume each worker works exactly five days.
Suzy ID 123 worked 31.4 hours: 6.3 / day
Brad ID 456 worked 36.8 hours: 7.36 / day
Jenn ID 789 worked 39.5 hours: 7.9 / day
Exercise Answer
hours.py
1 input = open("hours.txt")
2 for line in input:
3 id, name, mon, tue, wed, thu, fri = line.split()
4
5 # cumulative sum of this employee's hours
6 hours = float(mon) + float(tue) + float(wed) + \
7 float(thu) + float(fri)
8
9 print(name, "ID", id, "worked", \
10 hours, "hours: ", hours/5, "/ day"
Find the size of a file
spreadsheets
 The spreadsheet is a very popular, and
powerful, application for manipulating data
 Its popularity means there are many
companies that provide their own version
of the spreadsheet
 It would be nice if those different versions
could share their data
CSV, basic sharing
 A basic approach to share data is the
comma separated value (CSV) format
◦ it is a text format, accessible to all apps
◦ each line (even if blank) is a row
◦ in each row, each value is separated from the
others by a comma (even if it is blank)
◦ cannot capture complex things like formula
Spread sheet and corresponding CSV file
Even CSV isn't universal
 As simple as that sounds, even CSV
format is not completely universal
◦ different apps have small variations
 Python provides a module to deal with
these variations called the csv module
 This module allows you to read
spreadsheet info into your program
csv reader
 import the csv module
 open the file as normally, creating a file object.
 create an instance of a csv reader, used to
iterate through the file just opened
◦ you provide the file object as an argument to the
constructor
 iterating with the reader object yields a row
as a list of strings
things to note
 Universal new line is working by default
◦ needed for this worksheet
 A blank line in the CSV shows up as an
empty list
 empty column shows up as an empty
string in the list
csv writer
much the same, except:
 the opened file must have write enabled
 the method is writerow, and it takes a list
of strings to be written as a row
Code Listing 14.3
 This code listing is a good example of
reading, modifying and then writing out a
CSV file that could be read by a
spreadsheet
 It involves lots of slicing (and has
comments) so it is a good exercise
OS Module
What are Modules?
 Modules are files containing Python
definitions and statements (ex. name.py)
 A module’s definitions can be imported
into other modules by using “import
name”
 The module’s name is available as a global
variable value
 To access a module’s functions, type
“name.function()”
Way of Calling elements from
Module
Method 1
import <module name >
# access the elements using module name

Short cut
import <module name> as <new name>
Method 2
from <module name > import <element
name >
Method 3

from <module name > import *


Same name in different modules
More on Modules
 Modules can contain executable statements
along with function definitions
 Each module has its own private symbol table
used as the global symbol table by all
functions in the module
 Modules can import other modules
 Each module is imported once per
interpreter session
 reload(name)

 R.py rc.py
The Module Search Path
 The interpreter searches for a file named
name.py
◦ Current directory given by variable sys.path
◦ List of directories specified by
PYTHONPATH
◦ Default path (in UNIX - .:/usr/local/lib/python)
 Script being run should not have the same
name as a standard module or an error
will occur when the module is imported
Standard Modules
 Python comes with a library of standard modules described in
the Python Library Reference
 Some are built into interpreter
 >>> import sys
>>> sys.s1
‘>>> ‘
>>> sys.s1 = ‘c> ‘
c> print ‘Hello’
Hello
c>
 sys.path determines the interpreters’s search path for
modules, with the default path taken from PYTHONPATH
 Can be modified with append() (ex. Sys.path.append(‘SOMEPATH’)
The dir() Function
 Used to find the names a module defines
and returns a sorted list of strings
◦ >>> import mod
>>> dir(mod)
[‘_name_’, ‘m1’, ‘m2’]
 Without arguments, it lists the names
currently defined (variables, modules,
functions, etc)
 Does not list names of built-in functions and
variables
◦ Use _bulltin_to view all built-in functions and
variables
Packages
 “dotted module names” (ex. a.b)
 Submodule b in package a
 Saves authors of multi-module packages from worrying about
each other’s module names
 Python searches through sys.path directories for the package
subdirectory
 Users of the package can import individual modules from the
package
 Ways to import submodules
 import sound.effects.echo
 from sound.effects import echo
 Submodules must be referenced by full name
 An ImportError exception is raised when the package cannot
be found
Importing * From a Package
 * does not import all submodules from a
package
 Ensures that the package has been
imported, only importing the names of
the submodules defined in the package
 import sound.effects.echo
import sound.effects.surround
from sound.effects import *
Intra-package References
 Submodules can refer to each other
 Surround might use echo module
 import echo also loads surround module
 import statement first looks in the containing package
before looking in the standard module search path
 Absolute imports refer to submodules of sibling
packages
 sound.filters.vocoder uses echo module
from sound.effects import echo
 Can write explicit relative imports
 from . import echo
 from .. import formats
 from ..filters import equalizer
Packages in Multiple Directories
 _path_ is a list containing the name of the
directory holding the package’s _init_.py
 Changing this variable can affect futute
searches for modules and subpackages in
the package
 Can be used to extend the set of
modules in a package
 Not often needed
What is the os module
 The os module in Python is an interface
between the operating system and the
Python language.
 As such, it has many sub-functionalities
dealing with various aspects.
 We will look mostly at the file related
stuff
What is a directory/folder?
 Whether in Windows, Linux or on OS X,
all OS's maintain a directory structure.
 A directory is a container of files or other
directories
 These directories are arranged in a
hierarchy or tree
Computer Science tree
 it has a root node,
with branch nodes,
ends in leaf nodes
 the directory
structure is
hierarchy (tree)
Directory tree
 Directories can be organized in a
hierarchy, with the root directory and
subsequent branch and leaf directories
 Each directory can hold files or other
directories
 This allows for sub and super directories
◦ just like in subclass/superclass in chapter 12
file path is a path through the tree
A path to a file is a path through the
hierarchy to the node that contains a file

/bill/python/code/myCode.py
◦ path is from the root node /, to the bill
directory, to the python directory, to the code
directory where the file myCode.py resides
the / in a path
 think of / as an /

operator, showing
something is a /bill /fred

directory
 follow the path, the /python

leaf is either a
directory or file /code
a path String
 a valid path string for python is a string
which indicates a valid path in the
directory structure
 Thus '/Users/bill/python/code.py'
is a valid path string
different 'paths' for different os
 It turns out that each OS has its own way
of specifying a path
◦ C:\bill\python\myFile.py
◦ /Users/bill/python/myFile.py
 Nicely, Python knows that and translates
to the appropriate OS
Two special directory names
 The directory name '.' is shortcut for
the name of the current directory you are
in as you traverse the directory tree
 The directory name '..' is a shortcut
for the name of the parent directory of
the current directory you are in
Some os commands
 os.getcwd() Returns the full path of
the current working directory
 os.chdir(path_str) Change the
current directory to the path provided
 os.listdir(path_str) Return a
list of the files and directories in the path
(including '.')
Some more os commands
 os.rename(source_path_str,
dest_path_str) Renames a file or directory
 os.mkdir(path_str) make a new
directory. So
os.mkdir('/Users/bill/python/new'
) creates the directory new under the directory
python.
 os.remove(path_str)Removes the file
 os.rmdir(path_str) Removes the
directory, but the directory must be empty
the walk function
 os.walk(path_str) Starts at the
directory in path_str. It yields three
values:
◦ dir_name, name of the current directory
◦ dir_list, list of subdirectories in the
directory
◦ files, list of files in the directory
 If you iterate through, walk will visit every
directory in the tree. Default is top down
Walk example
os.path module
allows you to gather some info on a path's
existence
 os.path.isfile(path_str) is this a
path to an existing file (T/F)
 os.path.isdir(path_str) is this a
path to an existing directory (T/F)
 os.path.exists(path_str) the path
(either as a file or directory) exists (T/F)
os.path names
assume p = '/Users/bill/python/myFile.py'
 os.path.basename(p) returns 'myFile.py'
 os.path.dirname(p) returns
'/Users/bill/python'
 os.path.split(p) returns
['Users/bill/python','myFile.py']
 os.path.splitext(p) returns
'/Users/bill/python/myFile', '.py'
 os.path.join(os.path.split(p)[0],'other.
py') returns '/Users/bill/python/other.py'
List files with specific condition

ls *.py and ls plot*[1-4]*.dat reads

import glob
filelist1 = glob.glob(’*.py’)
filelist2 = glob.glob(’plot*[1-4]*.dat’)
List all files and folders in a folder
ls -a mydir and just ls -a

filelist1 = os.listdir(’mydir’)
filelist1 = os.listdir(os.curdir) # current folder
(directory)
filelist1.sort() # sort alphabetically
Check if a file or folder exists
The widely used constructions in Unix scripts for
testing if a file or folder exist are if [ -f $filename ];
then and if [ -d $dirname ]; then.

These have very readable counterparts in Python:


if os.path.isfile(filename):
inputfile = open(filename, ’r’)
...
if os.path.isdir(dirnamename):
filelist = os.listdir(dirname)
Remove a folder and all its subfolders
The rm -rf mytree command removes an entire
folder tree.

In Python, the cross-platform valid command


becomes

import shutil
shutil.rmtree(foldername)
Copy a file to another file or folder
The cp fromfile tofile construction applies shutil.copy
in Python:

shutil.copy(’fromfile’, ’tofile’)

Copy a folder and all its subfolders


The recursive copy command cp -r for folder trees is
in Python expressed :

shutil.copytree(sourcefolder, destination)
Run any operating system command

The simplest way of running another program from


Python is to use os.system:

os.system(cmd)
Utility to find strings in files
 The main point of this function is to look
through all the files in a directory
structure and see if a particular string
exists in any of those files
 Pretty useful for mining a set of files
What we already know
try-except suite to catch errors:
try:
suite to watch
except ParticularError
error suite
more of what we know
 try suite contains code that we want to
watch:
◦ if an error occurs the try suite stops and
looks for an except suite that can handle the
error
 except suite has a particular error it
can handle and a suite of code for
handling that error
Error Flow
Code Listing 14.5
continuing
Check for specific exceptions
 Turns out that you don’t have to check
for an exception type.You can just have an
exception without a particular error and
it will catch anything
 That is a bad idea. How can you fix (or
recover from) an error if you don’t know
the kind of exception
 Label your exceptions, all that you expect!
What exceptions are there?
 In the present Python, there is a set of
exceptions that are pre-labeled.
 To find the exception for a case you are
interested it, easy enough to try it in the
interpreter and see what comes up
 The interpreter tells you what the
exception is for that case.
Examples
>>> 100/0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
100/0
error ZeroDivisionError: integer division or modulo by zero
names
CAPS
matter! >>> open('badFileName')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
open('badFileName')
IOError: [Errno 2] No such file or directory: 'badFileName'
Dealing with problems
Two ways to deal with exceptions
 LBYL: Look Before you Leap
 EAFP: Easier to Ask Forgiveness than
Permission (famous quote by Grace
Hopper)
Look Before You Leap
 By this we mean that before we execute a
statement, we check all aspects to make
sure it executes correctly:
◦ if it requires a string, check that
◦ if it requires a dictionary key, check that
 Tends to make code messy. The heart of
the code (what you want it to do) is
hidden by all the checking.
Easier to Ask Forgiveness than
Permission
 By this we mean, run any statement you
want, no checking required
 However, be ready to “clean up any
messes” by catching errors that occur
 The try suite code reflects what you
want to do and the except code what
you want to do on error. Cleaner
separation!
Python likes EAFP
 Code Python programmers support the
EAFP approach:
◦ run the code, let the except suites deal
with the errors. Don’t check first.
Code Listing 14-6
Version 2, finally suite
 you can add a finally suite at the end of
the try/except group
 the finally suite is run as you exit the
try/except suite, no matter whether an
error occurred or not.
◦ even if an exception raised in the try suite was
not handled!
 Gives you an opportunity to clean up as you
exit the try/except group
finally and with
finally is related to a with statement:
 creates a context (the try suite)
 has an exit, namely execute the finally
suite
Version 3, else
 One way to think about things is to think of
the try as a kind of condition (an exception
condition) and the excepts as conditional
clauses
 if an exception occurs then you match the
exception
 the else clause covers the non-exception
condition. It runs when the try suite does
not encounter an error.
The whole thing
try:
code to try
except PythonError1:
exception code
except PythonError2:
exception code
except:
default except code
else:
non exception case
finally:
clean up code
Code Listing 14-7
invoking yourself, raise
 You can also choose to invoke the exception
system anytime you like with the raise
command
raise MyException
 you can check for odd conditions, raise
them as an error, then catch them
 they must be part of the existing exception
hierarchy in Python
Non-local catch
 Interestingly, the except suite does not
have to be right next to the try suite.
 In fact, the except that catches a try
error can be in another function
 Python maintains a chain of function
invocations. If an error occurs in a
function and it cannot catch it, it looks to
the function that called it to catch it
Make your own exception
 You can make your own exception.
 Exceptions are classes, so you can make a
new exception by making a new subclass:
class MyException (IOError):
pass
 When you make a new class, you can add
your own exceptions.
Code Listing 14.9
part 1
part 2
The file object atrributes:
Once a file is opened and you have one file object, you can get various information
related to that file.
Here is a list of all attributes related to file object:

Attribute Description
file.closed Returns true if file is closed, false otherwise.
file.mode Returns access mode with which file was opened.
file.name Returns name of the file.
file.readable Returns true if file readable, false otherwise.
File.writeable Returns true if file writeable, false otherwise.
Reading and Writing Files:
The file object provides a set of access methods to make our lives easier. We would
see how to use read() and write() methods to read and write files.
The write() Method:
 The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.
 The write() method does not add a newline character ('\n') to the end of the
string:
Syntax:
fileObject.write(string);
Example:
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\r\nYeah its
great!!\r\n");
fo.close()

The above method would create foo.txt file and would write given content in that
file and finally it would close that file. If you would open this file, it would have
following content
Python is a great language.
Yeah its great!!
Renaming and Deleting Files:
 Python os module provides methods that help you perform file-processing
operations, such as renaming and deleting files.
 To use this module you need to import it first and then you can all any related
functions.
The rename() Method:
The rename() method takes two arguments, the current filename and the new
filename.
Syntax:
os.rename(current_file_name, new_file_name)
Example:
import os
os.rename( "test1.txt", "test2.txt" )
The delete() Method:
You can use the delete() method to delete files by supplying the name of the file to
be deleted as the argument.
Syntax:
os.remove(file_name)
Example:
import os
os.remove("test2.txt")
Directories in Python:
All files are contained within various directories, and Python has no problem handling
these too. The os module has several methods that help you create, remove, and
change directories.
The mkdir() Method:
You can use the mkdir() method of the os module to create directories in the
current directory. You need to supply an argument to this method, which contains
the name of the directory to be created.
Syntax:
os.mkdir("newdir")
Example:
import os # Create a directory "test"
os.mkdir("test")
The chdir() Method:
You can use the chdir() method to change the current directory. The chdir()
method takes an argument, which is the name of the directory that you want to
make the current directory.
Syntax:
os.chdir("newdir")
Example:
import os
os.chdir("/home/newdir")
The getcwd() Method:
The getcwd() method displays the current working directory.
Syntax:
os.getcwd()
Example:
import os
os.getcwd()
The rmdir() Method:
The rmdir() method deletes the directory, which is passed as an argument in the
method.
Before removing a directory, all the contents in it should be removed.
Syntax:
os.rmdir('dirname')
Example:
import os
os.rmdir( "/tmp/test" )
File & Directory Related Methods:
There are three important sources which provide a wide range of utility
methods to handle and manipulate files & directories on Windows and
Unix operating systems. They are as follows:

◦ File Object Methods: The file object provides functions to manipulate


files.
◦ OS Object Methods.: This provides methods to process files as well as
directories.
Exercise
 Write a function input_stats that
accepts a file name as a parameter and
that reports the longest line in the file.
◦ example input file, carroll.txt:
Beware the Jabberwock, my son,
the jaws that bite, the claws that catch,
Beware the JubJub bird and shun
the frumious bandersnatch.
◦ expected output:
>>> input_stats("carroll.txt")
longest line = 42 characters
the jaws that bite, the claws that catch,
Exercise Solution
def input_stats(filename):
input = open(filename)
longest = ""
for line in input:
if len(line) > len(longest):
longest = line

print("Longest line =", len(longest))


print(longest)
Exercise
 Suppose we have this hours.txt data:
123 Suzy 9.5 8.1 7.6 3.1 3.2
456 Brad 7.0 9.6 6.5 4.9 8.8
789 Jenn 8.0 8.0 8.0 8.0 7.5

 Compute each worker's total hours and


hours/day.
◦ Assume each worker works exactly five days.
Suzy ID 123 worked 31.4 hours: 6.3 / day
Brad ID 456 worked 36.8 hours: 7.36 / day
Jenn ID 789 worked 39.5 hours: 7.9 / day
Exercise Answer
hours.py
1 input = open("hours.txt")
2 for line in input:
3 id, name, mon, tue, wed, thu, fri = line.split()
4
5 # cumulative sum of this employee's hours
6 hours = float(mon) + float(tue) + float(wed) + \
7 float(thu) + float(fri)
8
9 print(name, "ID", id, "worked", \
10 hours, "hours: ", hours/5, "/ day"
the tell() method
 The tell() method tells you the
current file position
 The positions are in bytes (think
characters for UTF-8) from the beginning
of the file
my_file.tell() => 42L
the seek() method
 the seek() method updates the
current file position to a new file index (in
bytes offset from the beginning of the file)
 fd.seek(0) # to the beginning of the
file
 fd.seek(100) # 100 bytes from beginning
counting bytes is a pain
 counting bytes is a pain
 seek has an optional argument set:
◦ 0: count from the beginning
◦ 1: count for the current file position
◦ 2: count from the end (backwards)
every read moves current forward
 every read/readline/readlines moves the
current pos forward
 when you hit the end, every read will just
yield '' (empty string), since you are at
the end
◦ no indication of end-of-file this way!
 you need to seek to the beginning to
start again (or close and open, seek is
easier)
with statement
open and close occur in pairs (or
should) so Python provides a shortcut, the
with statement
 creates a context that includes an exit
which is invoked automatically
 for files, the exit is to close the file
with expression as variable:
suite
File is closed automatically when
the suite ends
read(size=1)
 you can use the read() method to
read just one byte at a time, and in
combination with seek move around the
file and “look for things”. Once current is
set, you can begin reading again
Examples
file = open(‘file', 'r')
# This will print every line one by one in
the file
for each in file:
print (each)
# Python code to illustrate read() mode
file = open("file.text", "r")
print file.read()
More on CSV files
spreadsheets
 The spreadsheet is a very popular, and
powerful, application for manipulating data
 Its popularity means there are many
companies that provide their own version
of the spreadsheet
 It would be nice if those different versions
could share their data
CSV, basic sharing
 A basic approach to share data is the
comma separated value (CSV) format
◦ it is a text format, accessible to all apps
◦ each line (even if blank) is a row
◦ in each row, each value is separated from the
others by a comma (even if it is blank)
◦ cannot capture complex things like formula
Spread sheet and corresponding CSV file
Even CSV isn't universal
 As simple as that sounds, even CSV
format is not completely universal
◦ different apps have small variations
 Python provides a module to deal with
these variations called the csv module
 This module allows you to read
spreadsheet info into your program
csv reader
 import the csv module
 open the file as normally, creating a file object.
 create an instance of a csv reader, used to
iterate through the file just opened
◦ you provide the file object as an argument to the
constructor
 iterating with the reader object yields a row
as a list of strings
things to note
 Universal new line is working by default
◦ needed for this worksheet
 A blank line in the CSV shows up as an
empty list
 empty column shows up as an empty
string in the list
csv writer
much the same, except:
 the opened file must have write enabled
 the method is writerow, and it takes a list
of strings to be written as a row
Code Listing 14.3
 This code listing is a good example of
reading, modifying and then writing out a
CSV file that could be read by a
spreadsheet
 It involves lots of slicing (and has
comments) so it is a good exercise
os module
What is the os module
 The os module in Python is an interface
between the operating system and the
Python language.
 As such, it has many sub-functionalities
dealing with various aspects.
 We will look mostly at the file related
stuff
What is a directory/folder?
 Whether in Windows, Linux or on OS X,
all OS's maintain a directory structure.
 A directory is a container of files or other
directories
 These directories are arranged in a
hierarchy or tree
Computer Science tree
 it has a root node,
with branch nodes,
ends in leaf nodes
 the directory
structure is
hierarchy (tree)
Directory tree
 Directories can be organized in a
hierarchy, with the root directory and
subsequent branch and leaf directories
 Each directory can hold files or other
directories
 This allows for sub and super directories
◦ just like in subclass/superclass in chapter 12
file path is a path through the tree
A path to a file is a path through the
hierarchy to the node that contains a file

/bill/python/code/myCode.py
◦ path is from the root node /, to the bill
directory, to the python directory, to the code
directory where the file myCode.py resides
the / in a path
 think of / as an /

operator, showing
something is a /bill /fred

directory
 follow the path, the /python

leaf is either a
directory or file /code
a path String
 a valid path string for python is a string
which indicates a valid path in the
directory structure
 Thus '/Users/bill/python/code.py'
is a valid path string
different 'paths' for different os
 It turns out that each OS has its own way
of specifying a path
◦ C:\bill\python\myFile.py
◦ /Users/bill/python/myFile.py
 Nicely, Python knows that and translates
to the appropriate OS
Two special directory names
 The directory name '.' is shortcut for
the name of the current directory you are
in as you traverse the directory tree
 The directory name '..' is a shortcut
for the name of the parent directory of
the current directory you are in
Some os commands
 os.getcwd() Returns the full path of
the current working directory
 os.chdir(path_str) Change the
current directory to the path provided
 os.listdir(path_str) Return a
list of the files and directories in the path
(including '.')
Some more os commands
 os.rename(source_path_str,
dest_path_str) Renames a file or directory
 os.mkdir(path_str) make a new
directory. So
os.mkdir('/Users/bill/python/new'
) creates the directory new under the directory
python.
 os.remove(path_str)Removes the file
 os.rmdir(path_str) Removes the
directory, but the directory must be empty
the walk function
 os.walk(path_str) Starts at the
directory in path_str. It yields three
values:
◦ dir_name, name of the current directory
◦ dir_list, list of subdirectories in the
directory
◦ files, list of files in the directory
 If you iterate through, walk will visit every
directory in the tree. Default is top down
Walk example
os.path module
os.path module
allows you to gather some info on a path's
existence
 os.path.isfile(path_str) is this a
path to an existing file (T/F)
 os.path.isdir(path_str) is this a
path to an existing directory (T/F)
 os.path.exists(path_str) the path
(either as a file or directory) exists (T/F)
os.path names
assume p = '/Users/bill/python/myFile.py'
 os.path.basename(p) returns 'myFile.py'
 os.path.dirname(p) returns
'/Users/bill/python'
 os.path.split(p) returns
['Users/bill/python','myFile.py']
 os.path.splitext(p) returns
'/Users/bill/python/myFile', '.py'
 os.path.join(os.path.split(p)[0],'other.
py') returns '/Users/bill/python/other.py'
Code Listing 14.4
Utility to find strings in files
 The main point of this function is to look
through all the files in a directory
structure and see if a particular string
exists in any of those files
 Pretty useful for mining a set of files
 lots of comments so you can follow
More Exceptions
What we already know
try-except suite to catch errors:
try:
suite to watch
except ParticularError
error suite
more of what we know
 try suite contains code that we want to
watch:
◦ if an error occurs the try suite stops and
looks for an except suite that can handle the
error
 except suite has a particular error it
can handle and a suite of code for
handling that error
Error Flow
Code Listing 14.5
continuing
Check for specific exceptions
 Turns out that you don’t have to check
for an exception type.You can just have an
exception without a particular error and
it will catch anything
 That is a bad idea. How can you fix (or
recover from) an error if you don’t know
the kind of exception
 Label your exceptions, all that you expect!
What exceptions are there?
 In the present Python, there is a set of
exceptions that are pre-labeled.
 To find the exception for a case you are
interested it, easy enough to try it in the
interpreter and see what comes up
 The interpreter tells you what the
exception is for that case.
Examples
>>> 100/0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
100/0
error ZeroDivisionError: integer division or modulo by zero
names
CAPS
matter! >>> open('badFileName')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
open('badFileName')
IOError: [Errno 2] No such file or directory: 'badFileName'
Philosophy of Exception
Handling
Dealing with problems
Two ways to deal with exceptions
 LBYL: Look Before you Leap
 EAFP: Easier to Ask Forgiveness than
Permission (famous quote by Grace
Hopper)
Look Before You Leap
 By this we mean that before we execute a
statement, we check all aspects to make
sure it executes correctly:
◦ if it requires a string, check that
◦ if it requires a dictionary key, check that
 Tends to make code messy. The heart of
the code (what you want it to do) is
hidden by all the checking.
Easier to Ask Forgiveness than
Permission
 By this we mean, run any statement you
want, no checking required
 However, be ready to “clean up any
messes” by catching errors that occur
 The try suite code reflects what you
want to do and the except code what
you want to do on error. Cleaner
separation!
Python likes EAFP
 Code Python programmers support the
EAFP approach:
◦ run the code, let the except suites deal
with the errors. Don’t check first.
Code Listing 14-6
Extensions to the basic
Exception Model
Version 2, finally suite
 you can add a finally suite at the end of
the try/except group
 the finally suite is run as you exit the
try/except suite, no matter whether an
error occurred or not.
◦ even if an exception raised in the try suite was
not handled!
 Gives you an opportunity to clean up as you
exit the try/except group
finally and with
finally is related to a with statement:
 creates a context (the try suite)
 has an exit, namely execute the finally
suite
Version 3, else
 One way to think about things is to think of
the try as a kind of condition (an exception
condition) and the excepts as conditional
clauses
 if an exception occurs then you match the
exception
 the else clause covers the non-exception
condition. It runs when the try suite does
not encounter an error.
The whole thing
try:
code to try
except PythonError1:
exception code
except PythonError2:
exception code
except:
default except code
else:
non exception case
finally:
clean up code
Code Listing 14-7
Raising and creating your own
exceptions
invoking yourself, raise
 You can also choose to invoke the exception
system anytime you like with the raise
command
raise MyException
 you can check for odd conditions, raise
them as an error, then catch them
 they must be part of the existing exception
hierarchy in Python
Non-local catch
 Interestingly, the except suite does not
have to be right next to the try suite.
 In fact, the except that catches a try
error can be in another function
 Python maintains a chain of function
invocations. If an error occurs in a
function and it cannot catch it, it looks to
the function that called it to catch it
Make your own exception
 You can make your own exception.
 Exceptions are classes, so you can make a
new exception by making a new subclass:
class MyException (IOError):
pass
 When you make a new class, you can add
your own exceptions.
Code Listing 14.9
part 1
part 2

Das könnte Ihnen auch gefallen