Fundamentals of Python: From First Programs Through Data Structures
ISYS90088
Introduction to Application Development
Contd. from Week 3 lectures– if , if-else,
Week 4 lectures –nested if, string sequences,
Loops – for
Department of Computing and Information Systems
University of Melbourne
Semester 2 , 2018
Dr Antonette Mendoza
1
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
2
Recap – Selection: if and if-else Statements
• Selection statements allow a computer to make choices –
based on a condition
• The if statement is used to create a decision structure, which
allows a program to have more than one path of execution.
• The if statement causes one or more statements to execute
only when a Boolean expression is true.
• It is a control structure – a logical design that controls the
order in which a set of statements execute.
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of
Python: First Programs
3
Recap – The if – else statement
• The simplest is a one-way selection statement (if)
• Also called a two-way selection statement (if-else)
• The condition in the if-else statement must be a Boolean
expression – that is, an expression that evaluates to either true
or false
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
4
Recap – if-else Statements
• The two possible actions each consist of a sequence of
statements
• Each sequence must be indented at least one space beyond
the symbols if and else.
Syntax:
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
5
Recap – if-else Statements (continued)
must be a Boolean expression
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 6
Multi-way if Statements (continued)
• At most one of the indented blocks will run.
• The conditions are tried in order until one is found that is True.
The associated block of code is run and any remaining
conditions and blocks are skipped.
• If none of the conditions are True but there is an else block,
then Python runs the else block.
Syntax:
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
7
Logical Operators and Compound Boolean
Expressions with if-else
• Often a course of action must be taken if either of two conditions
is true: Below are two approaches
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 8
Example: Multi-way if Statements
(continued)
Write a program to convert numeric grades of your ISYS90088 test
scores to letter grades. The grades are as follows:
– H1 all grades 80 and above(80 – 100)
– H2A all grades equal to and above 75 but below 80 (75-79)
– H2B all grades between grades(70-74)
– P all grades between (50 -69)
– F all grades below 50
Example ( using Idle)
Strings manipulations!
• Access individual characters in a string
• Retrieve a substring from a string
• Search for a substring in a string
• Using library for string manipulations
• Splitting a string into lists that can be manipulated
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 9
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 10
Accessing Characters and Substrings in
Strings
• In this section, we examine the internal structure of a
string more closely
• You will learn how to extract portions of a string called
substrings
11
The Structure of Strings
• Data structure – it is an organized way of storing and
representing data so that data can be inserted and accessed – data
structure consists of smaller pieces of data.
• A string is a data structure.
• The string is a sequence of zero or more characters
• A string is an immutable data structure. That means, its internal
data elements, the characters, can be accessed, but the structure
itself cannot be modified.
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 12
The Structure of Strings
• We sometimes might want to access or inspect characters at a
given position without needing to visit the entire string (part of a
string – substring)
• The string is arranged as shown. There is an index that helps us
step thru’ or inspect a position
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
13
Indexing and the Subscript Operator
• The form of the subscript operator is:
• Examples:
index is usually in range [0,length of string – 1];
can be negative
Why?
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 14
Strings indexing
• For example: String’s length – Number of characters it contains
(0+). len is a library function that allows us to do some
manipulation with strings.
Example:
>>>s = “example”
>>>s[2]
‘a’
15
Negative Indexing
• We have seen what happens when the index is too large. What
happens if the index is less than 0? Does it give us an error? NO
>>>s = “The number is 42.”
>>>print(s[-1])
>>>print(s[-2])
>>>print(s[-3])
>>>print(s[-17])
• Negative indices work from the end of the string, so -1 indexes
the last character, which is ??. and -17 indexes the 17th last
character, which is T (actually the first character of the string).
• Note the negative indexes are one-offset (i.e. start from -1) while
the positive indexes are zero-offset (i.e. start from 0).
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
16
Slicing for Substrings
• Python’s subscript operator can be used to obtain a
substring through a process called slicing
– Place a colon (:) in the subscript; an integer value can appear
on either side of the colon
• For example, the following code accesses the substring of
the string “the example is on slicing” starting at index 2, up
to (but not including) index 10.
>>>s = “the example is on slicing”
>>>print (s[2:10])
e exampl
Accessing Substrings (Slicing)
• The notation 2:10 is known as a slice.
• Remember that a slice starts at the first index but finishes one
before the end index. This is consistent with indexing: indexing
also starts from zero and goes up to one before the length of the
string.
• You can see this by slicing with the value of len:
>>>s = “the example is on slicing”
>>print (len(s))
>>print (s[0:len(s)])
17ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of
Python: First Programs
More on Slicing: example
18
• You can also slice with negative indices. The same basic rule of
starting from the start index and stopping one before the end
index applies:
>>>s = ”testing slicing 101″
>>>print(s[4:-7])
>>>print(s[-7:-1])
>>>print(s[-6:len(s)])
Solution:
????
Example – check example using IDLE
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of
Python: First Programs
More on slicing: example
• Python provides two shortcuts for common slice values:
– if the start index is 0 then you can leave it blank
– if the end index is the length of the string then you can leave it
blank
>>>s = ”testing slicing 101”
>>>print(s[:5])
>>>print(s[5:])
>>>print(s[:])
Solution:???
19
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
20
Changing the Step Size and Direction
• You can specify a third number which indicates how much to
step through the list by.
• For example, if you want every second element you can do
this:
>>>s = “abcdef”
>>>print(s[::2])
• Or you can specify a range with a step:
>>>s = “abcdef”
>>>print(s[0:3:2])
Example – show using IDLE!
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
21
Changing the Step Size and Direction
• If this third number is -1 it changes the direction you are slicing in:
>>>s = “abcdef”
>>>print(s[2::-1])
>>>print(s[2:0:-1])
>>>print(s[-4:-6:-1])
cba
cb
cb
• Note that the direction of the indices must be changed also. If
there is nothing in between the indices, an empty string is returned
(unlike indexing beyond the ends of the string, which led to an
error):
>>>s = “abcdef”
>>>print(s[0:2:-1])
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First
Programs
22
String Methods (continued)
• Methods can expect arguments and return values
• A method knows about the internal state of the object with
which it is called
• In Python, all data values are objects
• dir(str) or help(str) will give you the entire list of string
methods or library functions.
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
23
String Methods (continued)
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 24
String Methods (continued)
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
25
String Methods (continued)
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 26
String Methods (continued)
list method
• The method list() takes sequence types and converts them to
lists.
Syntax:
list(seq)
>>> num = ‘123’
>>> list(num)
[‘1’, ‘2’, ‘3’]
27
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
29
Testing for substring with the in Operator
• When used with strings, the left operand of in is a target
substring and the right operand is the string to be searched
– Returns True if target string is somewhere in search string,
or False otherwise
• Example:
>>>list = [“ant”, “dog”, “cat”, “rat”, “horse”]
>>>”ant” in list
True
(run example code for counting vowels)
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
30
An example for split
Example:
>>>S= ‘this is an example’
>>>listofitems = s.split()
>>>print(listofitems)
example(1)
31
Example : program – try this one!
# Imagine you are writing a title for a business report in your
organization. The title should be not more that 10 words.
Write a program that accepts from the user the title and :
i. Makes sure the title is in upper case. If its not, your
program converts the title to all upper case;
i. counts the number of words in the title. If the number of
words is >10, your program will inform the user that the
title must be not more that 10 words.
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
Example : fill in the XXX !
text = input(“enter a sentence :”)
If XXX:
text = text.upper()
print(‘your title in uppercase is’, text)
listofwords =XXX
if XXX > 10:
print(“your title must not exceed 10 words”)
else:
print (“there are”, XXX, “words in this title”)
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
Example : fill in the XXX !
text = input(“enter a sentence :”)
If text.islower():
text = text.upper()
print(‘your title in uppercase is’, text)
listofwords =text.split()
If listofwords > 10:
print(“your title must not exceed 10 words”)
else:
print (“there are”, len(listofwords), “words in this title”)
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
Break
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of
Python: First Programs
34
Loops in Python
• Python programming language provides following types of loops
to handle looping requirements.
• Why do we need loops?
• Types of loops:
➢ for loop: Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
➢ while loop: Repeats a statement or group of statements while a
given condition is TRUE. It tests the condition before executing the
loop body.
➢ nested loops: can use one or more loop inside any another while,
for or do..while loop.
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
35
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
36
The for Loop
• Repetition statements (or loops) repeat an action
• Each repetition of action is known as pass or iteration
• Python’s for loop is the control statement that supports
definite iteration
• A for loop helps with control, counting and repetition
The for loop
• It has the ability to iterate over the items of any sequence, such as
a list or a string.
Syntax:
for iterating_var in sequence:
• If a sequence contains an expression list, it is evaluated first.
Then, the first item in the sequence is assigned to the iterating
variable iterating_var. Next, the statements block is executed.
• Each item in the list is assigned to iterating_var, and the
statement(s) block is executed until the entire sequence is
exhausted.
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
37
The for loop
ISYS90088: some
slides adapted from
Fundamentals of
38
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 39
Examples of for loops: using list and strings
#example 1 – this is one way of doing it
for num in [1, 2, 3, 4, 5]:
print (num)
#example 2 – this is another way of doing it using lists
listofitems = [1, 2, 3, 4, 5]:
for num in listofitems:
print (num)
# Example using strings
for letter in ‘Python’:
print (‘Current Letter :’, letter)
# Second Example using strings
fruits = [‘banana’, ‘apple’, ‘mango’]
for fruit in fruits:
print (‘Current fruit :’, fruit)
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 40
Traversing the Contents of a Data Sequence
• Strings are also sequences of characters
• Values in a sequence can be visited with a for loop:
• Example: character is called the target variable- that takes a
value of each loop iteration
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 41
Executing a Statement a Given Number of
Times using the range function
• The form of this type of loop is:
loop header
statements in body must be indented and aligned in the same
column
loop body
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 42
Traversing the Contents of a Data Sequence
• range returns a list
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 43
Executing a Statement a Given Number of
Times (continued)
• Example: Loop to compute an exponentiation for a non-
negative exponent
• The variable product is called an accumulator
• If the exponent were 0, the loop body would not execute and value of
product would remain as 1
apple
高亮
apple
高亮
apple
附注
the truth here is find 2**3 = 8
2**1=2
2**2 = 2**1(上一次运行的结果)*2=4
2**3 = 2**2 *2 = 8
if expnent = 5, then result would be 2**5
for loop is an iteration( a repeat game); 像是这道题,range(3)就是说下面的这个block 运行 3 次 (当是0的时候,不运行)
apple
高亮
apple
高亮
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 44
Count-Controlled Loops
• Loops that count through a range of numbers
• To specify an explicit lower bound:
>>>product = 1
>>>for count in range(1:5):
product = product * count
>>>product
24
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 45
Count-Controlled Loops (continued)
• Example: bound-delimited summation
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
46
Note: Augmented Assignment
• Augmented assignment operations:
• Format:
Equivalent to:
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 47
Loop Errors: Off-by-One Error
• Example – if you want to count from 1 to 4???????:
Loop actually counts from 1 through 3
• This is not a syntax error, but rather a logic error
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 48
Specifying the Steps in the Range
• range expects a third argument that allows you specify a
step value
• Example in a loop:
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 49
Loops That Count Down
• Example:
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 50
Quiz
1. Write the output of the following loops:
a. for count in range(5)
print(count +1, end= ” “)
b. for count in range(1, 4):
print(count)
c. for count in range(1, 6, 2):
print(count)
d. for count in range(6, 1, -1):
print(count)
Example
#write a program in python that displays numbers starting from
#through to a user’s requirement and their squares in a table
#student ex: fill the places marked XXX with accurate
#statements that satisfies the requirement of the question
start = xxx
end = xxx
print (‘Number\t Square’)
print(‘————–‘)
for num in range (xxx, xxx):
square = num **2
print(num, ‘\t’, square)
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
51
• Break ( if time permits continue)
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 52
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
53
Conditional Iteration: The while Loop
• The while loop can be used to describe conditional
iteration
– Example: A program’s input loop that accepts values
until user enters a ‘sentinel’ that terminates the input
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
54
The Structure and Behavior of a while
Loop
• Conditional iteration requires that condition be tested
within loop to determine if it should continue
– Called continuation condition
– Improper use may lead to infinite loop
• while loop is also called entry-control loop
– Condition is tested at top of loop
– Statements within loop can execute zero or more times
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
55
The Structure and Behavior of a while
Loop (continued)
data is the loop control variable
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 56
The Structure and Behavior of a while
Loop (continued)
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
57
Count Control with a while Loop
ISYS90088: some slides adapted from Fundamentals of Python: First
Programs
58
The while True Loop and the break
Statement
• while loop can be complicated to write correctly
– Possible to simplify its structure and improve its
readability
ISYS90088: some slides adapted from Fundamentals of Python: First
Programs
59
The while True Loop and the break
Statement (continued)
• Alternative: Use a Boolean variable to control loop
break statement
• It terminates the current loop and resumes execution at the next
statement, just like the traditional break statement in C.
• The most common use for break is when some external condition
is triggered requiring a hasty exit from a loop. The break
statement can be used in both while and for loops.
• If you are using nested loops, the break statement stops the
execution of the innermost loop and start executing the next line
of code after the block.
Syntax:
>>> break
ISYS90088: some
slides adapted from
Fundamentals of
60
break statement
Example
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 61