Docsity

Python Loops: Definite vs Indefinite, Parameters and Mutable Objects, Study notes of Software Engineering

Partial preview of the text

Download Python Loops: Definite vs Indefinite, Parameters and Mutable Objects and more Study notes Software Engineering in PDF only on Docsity!

PARAMETERS, INDEFINITELOOPS, AND LOOP PATTERNS CSSE 120—Rose Hulman Institute of Technology

A better fix for the Eclipse PyDevinput bug (we think)

Download the win_in.py file from ANGEL (Modulesto Download

Æ

Session 10), and follow the

directions there.

Once you have done that, and renamed your inputand raw_input invocations as described there, youshould be able to use

Run as…

in Eclipse instead of

having to remember to use

External tools

Parameter Passing in Python

Formal parameters only receive the

values

of the

actual parameters

Assigning a new value to a formal parameter doesnot affect the actual parameter

Python passes parameters

by value

How should we fix

awardEC

Full Credit for Getting It Right

def awardEC(score, extra):

newScore = score + extra return

newScore

earned = 87bonus = 4 earned =

awardEC(earned, bonus)

print earned

A Central Parameter Example

Can we write a function that exchanges the values of its twoparameters?

attempt to exchange two integers def swapInts(x, y): x,y = y,x

attempt to exchange two elements of a list def swapListElements(list, i, j): list[i], list[j]

list[j], list[i] x,y

print 'Before "swapInts": x=%d, y=%d' %(x, y) swapInts (x, y) print 'After "swapInts": x=%d, y=%d' %(x, y) aList

= [3,

6]

print "Original list:",aList swapListElements(aList,

print "New list after swapListItems:", aList

Review: Definite Loops

Review: For loop^ †

Definite loop: knows

a priori

the number of iterations

of loop body

†

Counted loop: sequence can be generated by range()

†

Example for loop in slideshow.py

Syntax:^ †

for in :

Indefinite Loops

Number of iterations is not known when loop starts

Is a conditional loop^ †

Keeps iterating as long as a certain condition remainstrue

†

Conditions are Boolean expressions

Implemented using while statement

Syntax: while :

While Loop

A

pre-test loop

†

Condition is tested at the top of the loop

Example use of while loopsNadia deposits $100 in a savings account eachmonth. Each month the account earns 0.25%interest on the previous balance. How many monthswill it take her to accumulate $10.000?

Summary: Two main types of loops

Definite Loop^ †

We know at the beginning of the loop how many times itsbody will execute

†

Implemented in Python as a

for

loop.

Indefinite loop^ †

The body executes as long as some condition is true.

†

Implemented in Python as a

while

loop.

†

Can be an infinite loop if the condition never becomesFalse.

Python's

for line in file:

construct

†

indefinite loop that looks syntactically like a definite loop!

Some indefinite loop patterns

Interactive loops

Sentinel loops

File loops

post-test loops

"loop and a half"

User no longer has to count, but still has a big burden.

Interactive: Ask user if there is more

This initial value makes the loopexecute the first time through # average2.py #

A

**program to average a set of numbers

Illustrates interactive loop with two accumulators from** win_in import

def main(): moredata

"yes" sum

count

while moredata[0]

'y': x

win_input( "Enter a number

sum

sum

  • x count

count

moredata

win_raw_input( "Do you have more numbers (yes or no)?

print "\nThe average of the numbers is", sum

count

Sentinel loop

For this program, a negative input number isthe sentinel that signals "no more data"

User signals end of data by a special "sentinel"value.

Note that the sentinel value is not used in calculations.

**# average3.py # A program to average a set of numbers

Illustrates sentinel loop using negative input as sentinel from** win_in import

def main(): sum = 0.0 count = 0 x = win_input( "Enter a number (negative to quit) >> ") while x >= 0: sum = sum + x count = count + 1 x = win_input( "Enter a number (negative to quit) >> ") print "\nThe average of the numbers is", sum / count

Interactive loop with graphics

Display a window that contains a circle and amessage saying "Click inside Circle".

Whenever the user clicks outside the circle, display"You missed!"

If the user clicks inside the circle, display "Bull'seye!". Then pause and close the window.

File loop 1: using

for

Use a

for

loop as we have seen before:

Also note the conditional execution of

main()

# average5.py # Computes the average of numbers listed in a file. from win_in import

def main(): fileName = win_raw_input( "What file are the numbers in? ") infile = open(fileName, 'r') sum = 0.0 count = 0 for line in infile: sum = sum + eval(line) count = count + 1 print "\nThe average of the numbers is", sum / count if name == 'main': main()