代写 python ISYS90088

ISYS90088
Introduction to Application
Development
Contd. from Week 4 lectures – for using the range function
Week 5 lectures –nested for, while; formatting
Department of Computing and Information Systems University of Melbourne Semester 2 , 2018
Dr Antonette Mendoza
sem 2 2018
1

Objectives
• For and nested for statement • While statement
• Examples
• Formatting and examples
sem 2 2018
2

Loops in Python
• Python programming language provides following types of loops to handle looping requirements.
• 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 while loop.
sem 2 2018 3

Executing a Statement a Given Number of Times using the range function
• The form of this type of loop is:
loop body
statements in body must be indented and aligned in the same column
loop header
sem 2 2018
4

Traversing the Contents of a Data Sequence
• range returns a list
sem 2 2018
5

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
sem 2 2018
6

Count-Controlled Loops
• Loops that count through a range of numbers
• To specify a explicit lower bound:
sem 2 2018
7

Count-Controlled Loops (continued) • Example: bound-delimited summation
sem 2 2018
8

Loop Errors: Off-by-One Error • Example:
Loop actually counts from 1 through 3
• This is not a syntax error, but rather a logic error
sem 2 2018
9

Specifying the Steps in the Range • range expects a third argument that allows you
specify a step value • Example in a loop:
sem 2 2018
10

Loops That Count Down • Example:
sem 2 2018 11

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)
sem 2 2018
12

Nested for loops
Syntax for nested for:
for iterating_var in sequence:
for iterating_var in sequence: statements(s)
statements(s)

Nested for loops
#simple example to illustrate the nested for
n = int(input(‘enter a number:’))
for i in range(1,n):
for j in range(1,n):
print (i, j)
print(“good bye”)

Nested loops – when do we use it?
Example: For every word (in a list), look at every character in that word. This construct might look like this:
listofWord = [‘cat’, ‘dog’, ‘fish’] for word in listofWord:
for letter in word:
< do something....>
sem 2 2018 15

Examples: A simple nested for loop
“””
Example of code that draws out the following: say n = 5, then your drawing will look like:
#
## ### #### ##### “””
symbol = ’#’
number = int(input (‘enter a number:’)) for x in range(1, number+1):
s = “#”
for y in range(x-1):
s += symbol print (s)
sem 2 2018 16

Examples: A simple nested for loop Example code that checks whether numbers between 1 and 10 are prime.
## to calculate if a number is prime or not
for num in range(1,10): #to iterate between 1 to 10
for i in range(2,num): #to iterate on the factors of the number
if num%i == 0: #to determine the factor print (num, ‘is not prime’)
break
else:
print (num, ‘is a prime number’)
• Try doing this using a while as home work!!!!!
sem 2 2018 17

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
sem 2 2018
18

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
sem 2 2018 19

Structure and Behavior of a while Loop
sem 2 2018 20

Structure and Behavior of a while Loop (continued)
data is the loop control variable
sem 2 2018 21

Count Control with a while Loop
For loop
Same task – but with a While loop
sem 2 2018 22

Nested while
Syntax for nested while:
while : while :
statement(s) statement(s)
sem 2 2018 23

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
sem 2 2018 24

The while True Loop and the break Statement (continued)
• Alternative:UseaBooleanvariabletocontrolloop
sem 2 2018 25

break statement
• Itterminatesthecurrentloopandresumesexecutionatthe
next statement
• Themostcommonuseforbreakiswhensomeexternal 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
sem 2 2018 26

break statement
Example
sem 2 2018 27

Example: try writing a for loop for this while
Example: This code checks whether a word contains digits or not.
word = input(‘enter a word:’)
found_digit = False
i=0
while (not found_digit) and i < len(word): if word[i].isdigit(): found_digit = True print("The word contains digits!") i=i+1 if not found_digit: print("The word does not contain digits!") sem 2 2018 28 When to use : for and while loop Simplest way to differentiate between the for and the while: • weusuallyuseforwhenthereisaknownnumberofiterations, and use while constructs when the number of iterations in not known in advance. • while loops are slightly "fiddlier" than for loops, in that we need to set up a test in the while condition, and make sure to update the variable in the test appropriately in the body of our code. • In programming, "fiddlier"/more lines of code tends to correlate with "greater margin for error", and as such for loops should be your default choice. • expect/aim to use for much more than while. s e m 2 2 92 0 1 8 Formatting for output sem 2 2018 30 Formatting Text for Output • Use formatting when we need output that has tabular format • Field width: Total number of data characters & additional spaces for a datum in a formatted string – This version contains format string, format operator %, and single data value to be formatted – To format integers, letter d is used instead of s • To format sequence of data values: 31 Formatting Text for Output (continued) • When the field width is positive, the datum is right justified • When the field width is negative, the datum is left justified • If the field width is less that or equal to the datum’s print length in characters, no justification is added. sem 2 2018 32 Examples sem 2 2018 33 Formatting Text for Output (continued) • To format data value of type float: where . is optional • Examples:
sem 2 2018 34

Formatting Text for Output (continued) • Examples:
Note: the width includes the place for the decimal point
sem 2 2018 35

Formatting: Quiz
>>>amount = 24.325
>>>print(‘your salary is $%0.2f’ % amount)
>>>print(‘The area is %0.1f’ % amount)
>>>print(‘%10.4f’ % amount)
>>>print(‘%.5s’ % (‘tropical’))
>>>print(‘%5s’ % (‘tropical’))
>>>print(‘%5s’ % (‘trop’))
sem 2 2018 36

Example : formatting quiz
• Write a code segment that displays the values of the integers x, y, z on a single line, such that each value is right-justified in six columns.
• Then try the same as above but left justified
• Then try out the same as above but with the
values of x, y and z printed on separate lines
sem 2 2018 37

Example : formaLng
• Writeacodesegmentthatdisplaysthevaluesoftheintegersx,y, z on a single line, such that each value is right-justified in six columns.
>>>print(“%6d%6d%6d” % (x, y, z))
• Thentrythesameasabovebutleftjustified >>>print(“%-6d%-6d%-6d” % (x, y, z))
• Thentryoutthesameasabovebutwiththevaluesofx,yandz printed on separate lines
>>>print(“%6d\n%6d\n%6d” % (x, y, z)) >>>print(“%-6d\n%-6d\n%-6d” % (x, y, z))
(check out many more examples on LMS)
sem 2 2018 38

Formatting multiple values
Syntax:
print ( % (num, num …))
Note: same number of formaLng specifiers as values are needed for formaLng
>>>val1 = 6.7891234
>>>val2 = 1.2345678
>>>val3 = 123456789.123456789
>>>print(’values are %.1f and %.3f and %6.2f’ %(val1, val2, val3))
sem 2 2018 39

Formatting values: exercise – try this one!
>>>my_value = 7.2386
>>>print(‘%0.2f’ % my_value)
>>>amt = 5000.0
>>>m_pay = amt/12.0
>>>print(‘%0.2f’ % m_pay)
>>>my_new_value = 1.123456789
>>>print(‘%.2f’ % my_new_value)
>>>print(‘%.4f’ % my_new_value)
>>>print(‘%6.2f’ % my_new_value)

Formatting strings
>>> s = ‘mysterious’
# 7 characters in the string
>>>print(‘%.*s’ % (7, s))
# two characters in the string
>>>print(‘%.*s’ % (2, s))
###exponent
>>>print(‘%10.3e’ % (2000.345))
>>>print(‘%10.2E’ % (3456.234))
>>> x = 2000000
>>> print(‘%10e’ % x)
sem 2 2018 41

Formatting numbers and strings
Note:
• specifying a minimum field width – is the minimum number of spaces that should be used to display a value
• the field width specifies the number of spaces reserved on the screen for the value.
• if the value is shorter than the field width, it is displayed and will be right justified (filled with spaces)
• if the value is too large to fit in the specified field width, the field is automatically enlarged to accommodate it.
sem 2 2018 42

Formatting: examples (new styling (vs) old style of formatting
• Old style syntax:
• New formaLng style syntax in general:
Old: New:
sem 2 2018 43

Formatting: new (vs) old approach
Signed numbers – By default only negative numbers are prefixed with a sign.
#Old
>>>print(‘%+d’ % (60))
>>>print(‘%d’ % ((-40)))
#New
>>>print(‘{:+d}’.format(60))
>>>print(‘{:d}’.format((-40)))

Formatting: examples (new styling)
#Examples for formaLng using the format()
# using <, >, ^ and a filler >>>print(‘{:_<10}'.format('test')) #left >>>print(‘{:_^10}’.format(‘test’)) #centered >>>print(‘{:_>10}’.format(‘test’)) #right >>>print(‘{:*>10}’.format(‘test’)) # * as a filler
Check other examples – file uploaded on LMS
sem 2 2018 45

Formatting: examples (new styling)
count = 10
total = 100
print(‘The number contains {} digits’. format(count))
print(‘The digits sum to {}’. format(total))
Output:
he number contains 10 digits
The digits sum to 100
Side notes – lots of them to check out! (see uploaded on the LMS. There are a few rule changes when you use the format() – new style of formatting
– Youmayusetheoldorthenewstyletoformat
sem 2 2018 46

Formatting: some more examples to try out!
# example that uses date and time method
>>>from datetime import datetime
>>>print(‘{:%Y-%m-%d %H:%M}’.format(datetime(2016, 2, 10, 4, 30)))
#example that uses a list
data = [4, 8, 15, 16, 23, 42]
print(‘{d[4]} {d[5]}’.format(d=data))
sem 2 2018 47