Docsity

Python Loops and Parameters: Understanding Mutable Objects and Sentinel Values, Study notes of Software Engineering

Partial preview of the text

Download Python Loops and Parameters: Understanding Mutable Objects and Sentinel Values and more Study notes Software Engineering in PDF only on Docsity!

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

Review: Python parameter passing

^ 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 actual parameters

by value

^ Can functions in Python mutate parameters?

Modifying Parameters

^ How do functions send information back?^ †^ Return statements^ †^ Mutating

parameters „^ Value of actual parameter must be a mutable object „^ State of the mutable object is changed „^ The actual parameter itself is NOT changed since it refers tothe same object „^ Parameter is still passed by value

Recap: 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!

Interactive: Make the user count

^ Open module averageUserCount.py and execute ittogether ^ When does the loop terminate? ^ Is this the best way to make the user enter input?^ †^ Why?^ †^ Why not?

Interactive: Ask user if there is more

^ Open module averageMoreData.py and execute ittogether ^ User no longer has to count, but still has a bigburden

Non-numeric Sentinel

^ What if negative numbers are legitimate values? ^ Open module averageOtherSentinel.py and studythe code^ †^ Execute it together^ †^ What is the sentinel? ^ Again note:

sentinel value is not used in calculations.

File loop

^ Open module averageFile.py and execute togetherwith input file numbers.txt ^ Uses a

for^ loop as we have seen before

^ Also note the conditional execution of

main()

Individual Exercise on Using loops

Define function

listAndMax()

in module

listMax.py

that

†^ Prompts the user to enter numbers, one at a time †^ Uses a blank line () as sentinel to terminate input †^ Accumulates the numbers in a list †^ Uses a loop to calculate the maximum value of the numbers †^ Returns two values:^ „^ the list of numbers entered in the order they were entered^ „^ the maximum value Define function

main()

in module

listMax.py

that

†^ Calls listAndMax() †^ Prints the list of numbers entered †^ Prints the maximum value of the list of numbers

  • Start homework When you are through with your individual exercisecommit your solutions to your svn repository Start working on homework