21
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Repetition Structures In this unit, we will cover the While loop. In the next unit we cover For loops.

Python Chapter 04 While Loop Notes

  • Upload
    fdgdfg

  • View
    20

  • Download
    6

Embed Size (px)

DESCRIPTION

Notes on while loop in python based on textbook by Tony Gaddis.

Citation preview

Slide 1

In this unit, we will cover the While loop. In the next unit we cover For loops.C H A P T E R 4Repetition StructuresCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyTopicsIntroduction to Repetition StructuresThe while Loop: a Condition-Controlled LoopCalculating a Running TotalInput Validation LoopsSentinalsCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyIntroduction to Repetition StructuresOften have to write code that performs the same task multiple timesDisadvantages to duplicating codeMakes program largeTime consumingMay need to be corrected in many placesRepetition structure: makes computer repeat included code as necessaryIncludes condition-controlled loops and count-controlled loopsCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyThe while Loop: a Condition-Controlled Loopwhile loop: while condition is true, do somethingTwo parts: Condition tested for true or false valueStatements repeated as long as condition is trueIn flow chart, line goes back to previous partGeneral format: while condition:statementsCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyThe while Loop: a Condition-Controlled Loop (contd.)

Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyThe while Loop: a Condition-Controlled Loop (contd.)In order for a loop to stop executing, something has to happen inside the loop to make the condition falseIteration: one execution of the body of a loopwhile loop is known as a pretest loopTests condition before performing an iterationWill never execute if condition is false to start withRequires performing some steps prior to the loopCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyCode Examples # This program calculates sales commissions. # Create a variable to control the loop. - Note this variable is not Booleankeep_going = 'y' # better style use Boolean, assign to true

# Calculate a series of commissions. while keep_going == 'y': #MUST change the value of keep_going inside the loop

# Get sales and commission rate - Note the indentation of next lines sales = float(input('Enter the amount of sales: ')) comm_rate = float(input('Enter the commission rate: ')) # Calculate the commission. commission = sales * comm_rate # Display the commission. print('The commission is $', \ format(commission, ',.2f'), sep='') # See if the user wants to do another one. keep_going = input('Do you want to calculate another' + \ 'commission (Enter y for yes): ') #ensures a finite loopCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyInfinite LoopsLoops must contain within themselves a way to terminateSomething inside a while loop must eventually make the condition falseInfinite loop: loop that does not have a way of stoppingRepeats until program is interruptedOccurs when programmer forgets to include stopping code in the loopTo avoid this, make it a general rule to change the while condition variable in the loop code.E.g. keep_going in the previous example.Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyCalculating a Running TotalPrograms often need to calculate a total of a series of numbersTypically include two elements:A loop that reads each number in seriesAn accumulator variableKnown as program that keeps a running total: accumulates total and reads in seriesAt end of loop, accumulator will reference the totalCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyCalculating a Running Total (contd.)

Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyCalculating a Running Total Code while keep_going : #now we use a Boolean what must the initial value be? number = int(input('Enter a number: ')) total = total + number # what should total be initialized to?count = count +1 # this would be useful to get the average if needed#code to set keep_going to false if user has no more entries

# Display the total of the numbers. - Note this is after the loop ends

print('The total is', total)The book shows this code in a for-loop.From the previous slide, can you see what the logic is and complete the code shown? This is for your own practice no need to post it.Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyLoops Best PracticesInitialize all variables that are changed inside the loop: counters, running totals, user-input, etc.Ensure the while condition starts at true otherwise loop will never executeEnsure while condition uses a variables that is CHANGED inside the loopEnsure that no code is placed inside the loop if it is not needed e.g. printing the final result.Last one: Use Boolean variables instead of y, n, or on, off cases. It make look longer in code but it is more efficient speed and space wise.Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyThe Augmented Assignment OperatorsIn many assignment statements, the variable on the left side of the = operator also appears on the right side of the = operatorAugmented assignment operators: special set of operators designed for this type of jobShorthand operatorsCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyThe Augmented Assignment Operators (contd.)

You dont have to use these but you need to know the syntax. Many programmers like it because it resembles C++.Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleySentinelsSentinel: special value that marks the end of a sequence of itemsWhen program reaches a sentinel, it knows that the end of the sequence of items was reached, and the loop terminatesMust be distinctive enough so as not to be mistaken for a regular value in the sequenceExample: when reading an input file, empty line can be used as a sentinel, or -1 when expecting user to enter grades.Can you think of other examples?

Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyInput Validation LoopsComputer cannot tell the difference between good data and bad dataIf user provides bad input, program will produce bad outputGIGO: garbage in, garbage outIt is important to design programs such that bad input is never acceptedCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyInput Validation Loops (contd.)Input validation: inspecting input before it is processed by the programIf input is invalid, prompt user to enter correct dataCommonly accomplished using a while loop which repeats as long as the input is badIf input is bad, display error message and receive another set of dataIf input is good, continue to process the input and end the loop via its conditionCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyInput Validation Loops (contd.)

Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleyInput Validation Code while score < 0 or score > 100: print('ERROR: The score cannot be negative') print('or greater than 100.') score = int(input('Enter the correct score: '))

What should score be initialized to so that the while condition starts at true?Only downside to this loop is it forces the user to enter a value within the range, even if they decided to quit the program. You can add if statement to end the loop.Copyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-WesleySummaryThis chapter covered:Repetition structures, including:Condition-controlled loopsInfinite loops and how they can be avoidedCalculating a running total and augmented assignment operatorsCopyright 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley