You are on page 1of 100

STRINGS

LOOPING AND COUNTING

Write a function that can determine the


number of occurrence of given letter
inside a string?
SEARCH PROBLEM
SEARCHING INSIDE A STRING

Find the first occurrence of a given


letter inside a string
STRING METHODS
A method is similar to a function

It takes arguments and returns a


value but the syntax is different.
EXAMPLES
>>> word = ‘test’
>>> new_word = word.lower ()
>>> print(new_word)
>>> print(word)
EXAMPLES

>>> word = ‘test test’


>>> i = word.find(‘s’)
>>> print(i)
EXAMPLES

>>> word = ‘test test’

>>> i = word.find(‘es’)

>>> print(i)
EXAMPLES

>>> word = ‘test test’

>>> i = word.find(‘es’, 3)

>>> print(i)
EXAMPLES

>>> word = ‘test test’

>>> i = word.find(‘t’, 1, 3)

>>> print(i)
THE in OPERATOR
>>> ‘n’ in ‘banana’
True
>>> ‘seed’ in ‘banana’
False
EXAMPLE

Write a function that can determine


letters that are shared by two words?
DATA
STRUCTURES
Data Structures In Python
WHAT ARE DATA
STRUCTURES?
In computer science, a data structure is a
particular way of organizing data in a computer
so that it can be used efficiently.
LISTS
 A List is a kind of Collection

 A collection allows us to put many values in a single

“variable”

 A collection is nice because we can carry many values

around in one convenient package.


LIST

friends_cast = [‘Chandler’, ‘Phoebe’, ‘Joey’]

marks = [12, 15, 9, 12, 20, 19]


LIST CONSTANTS
 List constants are surrounded by square brackets
and the elements in the list are separated by
commas.
 A list element can be any Python object - even
another list
 A list can be empty
EXAMPLES

>>> print([1, 24, 76] )

[1, 24, 76]

>>> print(['red', 'yellow', 'blue'] )

['red', 'yellow', 'blue']


EXAMPLES

>>> print([ 1, [5, 6], 7] )

[1, [5, 6], 7]

>>> print( [] )

[]
GO THROUGH THE LIST
for i in [5, 4, 3, 2, 1] : 5
4
print(i)
3
print('Blastoff!‘) 2
1
Blastoff!
LIST TRAVERSAL

Simpsons= [‘Homer', ‘Bart', ‘Lisa’, ‘Marge’]

for character in Simpsons:


print(character, ‘is in the Simpsons family’)
HOW LONG IS A LIST?
 The len() function takes a list as a parameter and returns

the number of elements in the list

 Actually len() tells us the number of elements of any set or

sequence (i.e. such as a string...)


LIST TRAVERSAL
car_makers = [‘Ford’, ‘Toyota’, ‘BMW’]

for car in range(len(car_makers)):


print(car_makers[car])
THE in OPERATOR

>>> ‘Ford’ in [‘Ford’, ‘Toyota’, ‘BMW’]


True
LIST OPERATIONS
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]
LIST OPERATIONS
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
LIST OPERATIONS
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3]
['b', 'c']
>>> a_list[:4]
['a', 'b', 'c', 'd']
LOOKING INSIDE LISTS
Just like strings, we can get at any single element in a
list using an index specified in square brackets

‘Homer’ ‘Bart' ‘Lisa’ ‘Marge’


0 1 2 3
UPDATING LISTS
friends_cast = [‘Chandler’, ‘Phoebe’, ‘Joey’]

friends_cast[0] = ‘Monica’

print(friends_cast)
MUTABILITY: LIST VS
STRINGS

Lists are mutable

Strings are immutable


STRING
>>> my_string = "TEST"
>>> my_string[2] = "X"

Traceback (most recent call last):


File "<pyshell#2>", line 1, in <module>
my_string[2] = 'x'
TypeError: 'str' object does not support item assignment
DEEP COPY & SHALLOW
COPY
>>> game_of_thrones = [‘Targaryen’, ‘Stark’]

>>> got_families = game_of_thrones


>>> got_families[0] = ‘Baratheon’
>>> print(game_of_thrones)
REVIEW: LISTS
 A List is a kind of Collection

 A collection allows us to put many values in a single

“variable”

 A collection is nice because we can carry many values

around in one convenient package.


REVIEW: LIST OPERATIONS
>>> a_list = ["a", "b", "c", "d", "e", "f"]
>>> a_list[1:3]
['b', 'c']
>>> a_list[:4]
['a', 'b', 'c', 'd']
REVIEW: LOOKING INSIDE
LISTS
Just like strings, we can get at any single element in a
list using an index specified in square brackets

‘Homer’ ‘Bart' ‘Lisa’ ‘Marge’


0 1 2 3
LIST ARGUMENTS

Write a function that determines the length


of a list
LIST APPEND METHOD

>>> t1 = [1, 2]

>>> t1.append(3)

>>> print(t1)

[1, 2, 3]
LIST INSERT METHOD

>>> l = [1, 2]

>>> l.insert (2,4)

>>> print(l)

[1, 2, 4]
LIST INSERT METHOD

>>> l = [1, 2]

>>> l.insert (23,4)

>>> print(l)

[1, 2, 4]
LIST INSERT METHOD

>>> l = [1, 2]

>>> l.insert (1,4)

>>> print(l)

[1, 4, 2]
LIST METHODS
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1)
[1,2,3]
>>> print(t2)
None
‘is’ OPERATOR
Given two strings

a = ‘banana’
b = ‘banana’

We know that a and b both refer to a string.


Are they referring to the same string?
‘is’ OPERATOR
>>> a = 'banana'
>>> b = 'banana'
>>> a == b
True
‘is’ OPERATOR
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
‘is’ OPERATOR
>>> a = [1,2]
>>> b = [1,2]
>>> a == b
True
‘is’ OPERATOR
>>> a = [1,2]
>>> b = [1,2]
>>> a is b
False
DEBUGGING
t = [1,2]
# add element 4 to list t
t.append([4])
t = t.append(4)
t + [4]
t=t+4
DICTIONARY
DICTIONARY

Dictionary is like a list, but more general.

In a list, the indices have to be integers; in a

dictionary they can be (almost) any type.


DICTIONARY

A dictionary is a mapping between KEYS and


set of Values.

key-value pair
DICTIONARY
 Lists index their entries based on the position in the list.

 Dictionaries are like bags - no order

 So we index the things we put in the dictionary with a

“lookup tag”
DICTIONARY

>>> eng2sp = {}
dict()

>>> print(eng2sp)

{}
DICTIONARY

>>> eng2sp[‘one’] = ‘uno’

>>> print(eng2sp)

{'one': 'uno'}
DICTIONARY

>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

>>> print(eng2sp)

{'three': 'tres', 'two': 'dos', 'one': 'uno'}


DICTIONARY

The order of the key-value pairs is not the same. In


fact, if you type the same example on your computer,
you might get a different result. In general, the order
of items in a dictionary is unpredictable.
DICTIONARY

>>> item_price = {}

>>> item_price[‘milk’] = 10

>>> print(item_price[‘milk’])

10
DICTIONARY

>>> item_price = {}

>>> item_price[‘milk’] = 10

>>> print(item_price[‘sugar’])

KeyError: ‘sugar’
DICTIONARY

>>> number_of_days = {‘January’: 31,


‘February’: 28, ‘March’: 31}

>>> number_of_days[‘February’]
ITERATION ON DICTIONARIES
Even though dictionaries are not stored in order, we can
write a for loop that goes through all the entries in a
dictionary - actually it goes through all of the keys in the
dictionary and looks up the values
ITERATION
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

for k in eng2sp:
print(k)
ITERATION: VALUES
eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

for k in eng2sp:
print(eng2sp[k])
‘in’ OPERATOR
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

>>> ‘one’ in eng2sp


True
>>> ‘uno’ in eng2sp
False
DEMO: CHARACTER
COUNTER
(HISTOGRAM)
WHAT DATA TYPES CAN NOT
BE KEYS
Keys inside a Python dictionary can only be of a
type that is immutable. Immutable data types in
Python are integers , strings , tuples , floating point
numbers , and Booleans . Dictionary keys cannot be
of a type that is mutable, such as sets , lists , or
dictionaries .
RETRIEVING LISTS OF KEYS
AND VALUES
>>> counts.keys()

>>> counts.values()

>>> counts.items()
Tuples
Tuples

 a sequence of values

 are indexed by integers

>>> t = ‘a’, ‘b’, ‘c’


Tuples

 Tuples are Immutable

>>> t = (‘a’, ‘b’, ‘c’)


Tuples

>>> t1 = ()

>>> t2 = (1)
(1,)
Tuple Assignment

a, b = 2, 3
Return values

def divmod(a,b):
return a//b, a%b
Dictionaries & Tuples

>>> d = {‘a’: 12, ‘b’: 18}

>>> t = d.items()

[(‘b’,18),(‘a’,12)]
Looping

for key, value in d.items():


print(key, ‘==>’, value)
Files
Lab07: File and Exceptions
Software What
Next?

Input Central
and Output Processing
Devices Unit
Secondary
if x< 3: print Memory

Main
Memory
Persistence?

 Programs we wrote so far: Transient

 Others: Persistent

 Web servers

 Operating Systems
File

Every computer system uses FILES to


save things from one computation to
the other
File Processing

Simplest way for programs to maintain


their data is by reading and writing text
files
File processing

Each operating system comes with its


own file system for creating and
accessing files but Python achieves
OS-independence by accessing files
through something called FILE
HANDLE.
Opening a File

Before we can read/write the contents of


the file we must tell Python which file we
are going to work with and what we will be
doing with the file
Opening a File

 This is done with the open() function

 open() returns a “file handle” - a

variable used to perform operations on


the file
open()
handle = open(filename, mode)

filename is a string
mode is optional and should be 'r' if we are
planning reading the file and 'w' if we are
going to write to the file
returns a handle use to manipulate the file
open modes
r
w
a
 rb
 wb
Text file processing

A text file can be thought of as a sequence

of lines
A text file has newlines at the end of each

line
File handle as a sequence
A file handle open for read can be treated as a
sequence of strings where each line in the file
is a string in the sequence
We can use the for statement to iterate through
a sequence
Remember - a sequence is an ordered set
File handle as a sequence

xfile = open('mbox.txt‘, ‘r’)


for line in xfile:
print(line)
xfile.close()
open()
mode read(‘r’) mode write(‘w’)
fh.read() fh.write(s)
fh.readline() fh.writelines(l)
fh.readlines()
IOError: [Errno 2]

>>> fhand = open('stuff.txt')


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2]

No such file or directory: 'stuff.txt '


PermissionError: [Errno 13]

>>> fout = open('/etc/passwd', 'w')

PermissionError: [Errno 13]

Permission denied: '/etc/passwd'


Exception

 Exception is ‘something that does not

conform to the norm’


 The error message: STACK TRACEBACK

or TRACEBACK
Exceptions

 Exceptions are RUN TIME ERRORS

 Unhandled exception: an exception that

causes a program to terminate… raise


Exception Handling
 Dealing with the exception

Code that may raise an exception


try:
<body>
except <exceptionType>:
<handle>
Sample code

success_failure_ratio = num_success/num_failure

print(‘success/failure = ’, success_failure_ratio)

What problem do you anticipate?


Division by zero
try:

success_failure_ratio = num_success/num_failure

print(‘success/failure = ’, success_failure_ratio)
except IOError:
ZeroDivisionError:
print(‘Division by zero’)
Back to opening file
try:
open(file_name, ‘r’)
except IOError:
print(‘File’, file_name, ‘does not exist’)
The try ... except Clause
try:
<body>
except <exceptionType1>:
<handle1>
except <excetpionType2> as e:
<handle2>
finally:
<finalize_process>
Best practices
Defensive programming
x,y = eval(input(‘Enter integers x,y for the ratio x/y: ’)
try:
print(‘x,y = ’, x/y)
except ZeroDivisionError:
print(‘division by zero’)
except:
raise ValueError(‘Bad Arguments’)
Defensive programming
x,y = eval(input(‘Enter x,y for the ratio x/y: ’)
assert type(x)==int and type(y) == int
try:
print(‘x,y = ’, x/y)
except ZeroDivisionError:
print(‘File’, file_name, ‘does not exist’)

You might also like