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
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
1
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
2
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 3 Python: First Programs
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
4
Recap – if-else Statements (continued)
must be a Boolean expression
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
5
• •
•
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 6
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
7
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)
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 8
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
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
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 10
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 11
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 12
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
13
•
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’
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs 14
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
15
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
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
16
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)])
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of 17 Python: First Programs
More on Slicing: example
• 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 18 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:???
ISYS90088 sem 2, 2018 – few slides adapted from Fundamentals of Python: First Programs
19
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
20
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
21
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 22 Programs
String Methods (continued)
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
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
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
29
An example for split
Example:
>>>S= ‘this is an example’ >>>listofitems = s.split() >>>print(listofitems)
example(1)
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
30
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
31
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 34 Python: First Programs
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.
35 ISYS90088: some slides adapted from Fundamentals of Python: First Programs
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
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
36
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.
37 ISYS90088: some slides adapted from Fundamentals of Python: First Programs
The for loop
ISYS90088: some 38
slides adapted from
Fundamentals of
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 39
• •
•
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
Traversing the Contents of a Data Sequence
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 40
Executing a Statement a Given Number of Times using the range function
•
The form of this type of loop is:
loop body
loop header
statements in body must be indented and aligned in the same column
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 41
Traversing the Contents of a Data Sequence
• range returns a list
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 42
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
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 43
•
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 44
Count-Controlled Loops (continued) • Example: bound-delimited summation
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
45
Note: Augmented Assignment • Augmented assignment operations:
• Format: Equivalent to:
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
46
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 47
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 48
Loops That Count Down • Example:
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 49
1.
Quiz
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)
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 50
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
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
53
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
54
The Structure and Behavior of a while Loop (continued)
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
Count Control with a while Loop
ISYS90088: some slides adapted from Fundamentals of Python: First Programs
57
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 58 Programs
The while True Loop and the break Statement (continued)
• Alternative: Use a Boolean variable to control loop
ISYS90088: some slides adapted from Fundamentals of Python: First 59 Programs
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 60
slides adapted from
Fundamentals of
break statement
Example
ISYS90088: some slides adapted from Fundamentals of Python: First Programs 61