0% found this document useful (0 votes)
1 views37 pages

03 - Problem Solving With Python 2

The document outlines a Python programming lesson focused on problem-solving with strings and lists, detailing key concepts such as string manipulation, list creation, and processing. It includes learning outcomes, important terms, and various functions and methods for working with strings and lists. The content is structured to guide learners in developing programming skills through practical examples and exercises.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views37 pages

03 - Problem Solving With Python 2

The document outlines a Python programming lesson focused on problem-solving with strings and lists, detailing key concepts such as string manipulation, list creation, and processing. It includes learning outcomes, important terms, and various functions and methods for working with strings and lists. The content is structured to guide learners in developing programming skills through practical examples and exercises.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Programming In Python

CT088-0-M version 1 (November 2017)

Problem solving with Python


Topic & Structure of the lesson

• strings
– Defining string type of data
– Searching through string / list
– Finding element in a string/ list
– Looping through string/ list
• List
– Creation
– Processing

Module Code and Module Title Title of Slides


Learning outcomes

• At the end of this lecture you should be


able to:
– Develop a problem-based strategy for
creating and applying programmed solutions
– Create, edit, compile, run, debug and test
programs using an appropriate development
environment

Module Code and Module Title Title of Slides


Key terms you must be able to
use
• If you have mastered this topic, you
should be able to use the following terms
correctly in your assignments and exams:

– str
– len
– list

Module Code and Module Title Title of Slides


String Data Type
• A string is a sequence of >>> str1 = "Hello”
>>> str2 = 'there'
characters >>> bob = str1 + str2
• A string literal uses >>> print(bob)
quotes 'Hello' or “Hello” Hellothere
>>> str3 = '123'
• For strings, + means >>> str3 = str3 + 1
“concatenate” Traceback (most recent call last): File
"<stdin>", line 1, in
• When a string contains <module>TypeError: cannot
numbers, it is still a string concatenate 'str' and 'int' objects
>>> x = int(str3) + 1
• We can convert numbers >>> print(x)
in a string into a number 124
using int() >>>

Module Code and Module Title Title of Slides


Reading and
Converting >>> name = input('Enter:')
Enter:Chuck
• We prefer to read data >>> print(name)
in using strings and Chuck
then parse and convert >>> apple = input('Enter:')
the data as we need Enter:100
>>> x = apple – 10
• This gives us more
Traceback (most recent call last): File
control over error "<stdin>", line 1, in
situations and/or bad <module>TypeError: unsupported
user input operand type(s) for -: 'str' and 'int'
• Raw input numbers >>> x = int(apple) – 10
must be converted from >>> print(x)
strings 90

Module Code and Module Title Title of Slides


Looking Inside Strings

• We can get at any single


character in a string using b a n a n a
an index specified in 0 1 2 3 4 5
square brackets
• The index value must be
an integer and starts at >>> fruit = 'banana'
>>> letter = fruit[1]
zero
>>> print(letter)
• The index value can be an a
expression that is >>> n = 3
>>> w = fruit[n - 1]
computed >>> print(w)
n

Module Code and Module Title Title of Slides


A Character Too Far

• You will get a


python error if you
attempt to index >>> zot = 'abc'
>>> print(zot[5])
beyond the end of Traceback (most recent call last): File
"<stdin>", line 1, in
a string. <module>IndexError: string index out
of range
• So be careful >>>

when constructing
index values and
slices
Module Code and Module Title Title of Slides
Strings Have Length

• There is a built-in
function len that b a n a n a
gives us the length 0 1 2 3 4 5
of a string
>>> fruit = 'banana'
>>> print(len(fruit))
6

Module Code and Module Title Title of Slides


Len Function

>>> fruit = 'banana' A function is some stored


>>> x = len(fruit) code that we use. A
>>> print x function takes some input
6 and produces an output.

'banana' len() 6
(a number)
(a string)
function

Module Code and Module Title Title of Slides


Looping Through Strings

• Using a while
statement and an
iteration variable, and
the len function, we fruit = 'banana' 0b
can construct a loop index = 0 1a
while index < len(fruit) : 2n
to look at each of the letter = fruit[index] 3a
letters in a string print index, letter 4n
individually index = index + 1 5a

Module Code and Module Title Title of Slides


Looping Through Strings

• A definite loop
using a for
statement is much
b
more elegant a
fruit = 'banana' n
• The iteration for letter in fruit : a
variable is print letter n
a
completely taken
care of by the for
loop

Module Code and Module Title Title of Slides


Looping Through Strings

• A definite loop
using a for fruit = 'banana'
for letter in fruit :
statement is much print letter b
more elegant a
n
• The iteration a
variable is n
index = 0 a
completely taken while index < len(fruit) :
care of by the for letter = fruit[index]
print letter
loop index = index + 1

Module Code and Module Title Title of Slides


Looping and Counting

• This is a simple
loop that loops
through each letter
in a string and word = 'banana'
count = 0
counts the number for letter in word :
of times the loop if letter == 'a' :
count = count + 1
encounters the 'a' print count
character.

Module Code and Module Title Title of Slides


Looking deeper into in

• The iteration variable


“iterates” though the
sequence (ordered set) Six-character string
• The block (body) of Iteration variable
code is executed once
for each value in the
sequence
• The iteration variable for letter in 'banana' :
moves through all of print letter
the values in the
sequence

Module Code and Module Title Title of Slides


Yes
Advance b a n a n a
Done?
letter

print letter

for letter in 'banana' :


print letter

The iteration variable “iterates” though the string and the block (body)
of code is executed once for each value in the sequence

Module Code and Module Title Title of Slides


M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11

• We can also look at any


continuous section of a
string using a colon >>> s = 'Monty Python'
operator >>> print s[0:4]
Mont
• The second number is >>> print s[6:7]
one beyond the end of the P
slice - “up to but not >>> print s[6:20]
Python
including”
• If the second number is
beyond the end of the
string, it stops at the end

Slicing Strings
Module Code and Module Title Title of Slides
M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11

• If we leave off the


first number or the >>> s = 'Monty Python'
>>> print s[:2]
last number of the Mo
slice, it is >>> print s[8:]
Thon
assumed to be the >>> print s[:]
beginning or end Monty Python

of the string
respectively

Slicing Strings
Module Code and Module Title Title of Slides
String Concatenation

• When the +
operator is >>> a = 'Hello'
applied to >>> b = a + 'There'
>>> print b
strings, it HelloThere
means >>> c = a + ' ' + 'There'
>>> print c
"concatenation" Hello There
>>>

Module Code and Module Title Title of Slides


Using in as an Operator

• The in keyword can


also be used to >>> fruit = 'banana’
>>> 'n' in fruit
check to see if one 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

Module Code and Module Title Title of Slides


String Library
• Python has a number of
string functions which are
in the string library
• These functions are
>>> greet = 'Hello Bob'>>> zap =
already built into every greet.lower()>>> print zaphello bob
string - we invoke them by >>> print greet
appending the function to Hello Bob>>> print 'Hi
There'.lower()
the string variable hi there
• These functions do not >>>
modify the original string,
instead they return a new
string that has been altered
Module Code and Module Title Title of Slides
>>> 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
Module Code and Module Title Title of Slides
http://docs.python.org/lib/string-methods.html
Module Code and Module Title Title of Slides
String Library

str.capitalize() str.replace(old, new[, count])


str.center(width[, fillchar]) str.lower()
str.endswith(suffix[, start[, end]]) str.rstrip([chars])
str.find(sub[, start[, end]]) str.strip([chars])
str.lstrip([chars]) str.upper()

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

Module Code and Module Title Title of Slides


Making everything UPPER CASE

• You can make a copy of a


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

Module Code and Module Title Title of Slides


Search and Replace

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

Module Code and Module Title Title of Slides


Stripping Whitespace

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

Module Code and Module Title Title of Slides


Prefixes

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


>>> line.startswith('Please')
True
>>> line.startswith('p')
False

Module Code and Module Title Title of Slides


What are list?

• Group similar items


• Python facilitate this with Lists.
• Should not be confused with Array module
of python, which gives more functionalities
• List are defined by square brackets
new_list = [3, 4, 5, 6]

Module Code and Module Title Title of Slides ‹#›


Creating a list

• To create an empty list in python


new_list = []
• To create a list with some elements
new_list = [3, 4, 5, 6]
new_list = list(range(10))
new_list = list(range(2,7))

Module Code and Module Title Title of Slides ‹#›


Adding data to list
• Create a list first
new_list = []
new_list = [3, 4, 5, 6]
new_list = list(range(10))
new_list = list(range(2,7))
• To add an element
new_list.append(3)# added to the end
new_list[4] = 145 # 5th element is
modified

Module Code and Module Title Title of Slides ‹#›


Important !!!
• Lists are heterogeneous:
• That is, the elements in a list need not be of the same
type, can have integers and strings together.
new_list.append(‘hello’)
new_list.append(123)
new_list[4] = 345
new_list[4] = ‘hi’
• Can even have another list as an element.
new_list1 = [3, 4, 5, 6]
new_list2 = [1,24, 45]
new_list1[2] = new_list2
new_list1.append(new_list2)

Module Code and Module Title Title of Slides ‹#›


View the list elements

• To view the contents of a list


print(new_list)
• We can index and slice the list, just like
strings
print(new_list[4])
print(new_list[0:3])

Module Code and Module Title Title of Slides ‹#›


List Processing

• Scan through the lists


for item in new_list:
print(item)
• Search for an element
for item in new_list:
if (item == 4):
print(item)

Module Code and Module Title Title of Slides ‹#›


List Processing

• Search for a name/string/text

new_list = ['John','Cat','Marry','Gold']
name = input("Enter a name to search for ")
for item in new_list:
if (item == name):
print(item)

Module Code and Module Title Title of Slides ‹#›


List functions
• append() # to add an element at the
end
• insert(0, 200) # insert at position 0
the element 200
• len(list_name)# return the length
• min(list_name)
• max(list_name)# return the min and
max so long as the list is well
defined
• sum(list_name)#returns the sum of
elements so long as they're numbers
Module Code and Module Title Title of Slides ‹#›

You might also like