CS 115 Lecture 10

CS 115 Lecture 10

CS 115 Lecture 8 Structured Programming; for loops Taken from notes by Dr. Neil Moore & Dr. Debby Keen The bad old days: GOTO In the early days of programming, we didnt have for loops, if statements, etc. Instead, we had just if this is true, go to 10. You could use that to skip over code (like an if does) or go back to an earlier line to make a loop This was very tedious and error prone Especially if something had to be changed

Spaghetti code: trying to trace a programs execution was like trying to trace one strand of spaghetti in a plate of it Structured programming In the 1960s, computer scientists started to think about how to write programs that were easier to understand and modify. Edsger Dijkstra, Go To Statement Considered Harmful (1968) They introduced the paradigm of structured programming. Patterns that lead to easier-to-understand code

Easier to test and debug Easier to modify and maintain Easier to collaborate on large programs Data structures and Control structures Weve already seen a little about data structures The ways of organizing data in a program Simple ones: constants and variables More complex: graphics objects, strings, lists, Control structures are ways of controlling the execution of a program

which statements execute, and in which order The three basic control structures In 1966, Bhm and Jacopini showed that any program using go to could be rearranged to use only three simple control structures Sequence Selection Iteration Added a fourth later: Subprograms (more in chapter 5) Each of these control structures has two important guarantees: Only one way to enter the control structure

Only one way to exit the control structure One entrance, one exit. The sequence control structure Sequencing or sequential execution just means: running one statement after another In Python we write one line after the next The default control structure Guarantees unique to sequence The steps will execute in the order given Steps will not be skipped It will always start at the first statement And finish at the last statement of the sequence

Selection control structure Selection means choosing which code to run based on a condition or question In Python, an if-else statement Two branches, based on True and False Each branch is another control structure (most often a sequence, can be a loop or another if) Guarantees: Always starts with the question/condition Runs one branch or the other, never both and never neither MUST do one of the two

Avoid dead code: code that is never executed not just not executed on one particular run, but NEVER executed Usually because the condition is always True or always False Iteration control structure Iteration means running code multiple times (a loop) In structured programming, repeat this body until a condition is false In Python, a while loop for loops are a special case of iteration Guarantees:

Always starts with the question/condition If the condition is True, executes the entire body, then comes back to the condition If the condition is False, leaves the loop Beware of infinite loops where the condition is always True Subprogram control structure Sometimes we need to repeat the same code in several different places It would be nice if we didnt have to write the code multiple times A subprogram is a chunk of the code treated as a single unit

When we need to execute that code, we call (invoke) the subprogram The call runs the subprogram, waits for it to finish Then execution keeps going from where the call is Sometimes we send values to the subprogram Sometimes the subprogram sends value(s) back Subprogram control structure

In Python, subprograms are called functions Arguments are the values we send to the function And the function can return a result (or results) Can you think of Python functions that Take one or more arguments? Take no arguments? Return a result? Dont return a result?

Subprogram control structure Guarantees for subprograms: Forces the invoking code to pause execution Starts execution at top of subprogram code Completes execution at bottom of subprogram Always returns execution control to the point where the subprogram was invoked Does NOT execute unless invoked (called) Control structures summary Sequence (one statement after another, easy to forget its name!)

Selection (conditionals: if and variations) Iteration (loops: for and while) Subprogram (functions: def and calls) Weve seen sequence and selection already, so now lets look at iteration in more detail. The for loop Syntax: for var in sequence: Followed by a block (collection of indented lines) called the body. The body must be indented more than the for line! var is an identifier (variable name)

Semantics; Execute the body once for each item in the sequence Each time, the variable var will have the value of that item Each run of the body is called an iteration. The for loop A very simple for loop: for color in (red, green, blue): print(color, is a primary color.) We give a tuple but a list in square brackets would

work too When executed, it does: Iteration 1: red is a primary color Iteration 2: green is a primary color Iteration 3: blue is a primary color Other kinds of sequences Strings can be used as sequences. Each iteration of the loop operates on a single character: name = input(What is your name? ) for char in name: print(char)

Prints this: J o h n Numeric ranges One of the most common, and most useful, kinds of sequences for a for loop is a numeric range. In Python, you create numeric ranges with the range function. It always creates integers. There are three ways to call range: range(3): counts from 0 up to 2 Computer scientists usually count from zero, not one Goes up to but not including the final number (just like randrange!)

for i in range(3): print(i, squared is, i**2) prints: 0 squared is 0 1 squared is 1 2 squared is 2 Note the loop ran 3 times (for i = 0, 1, and 2) Dont make a fencepost error! Range variations We can also tell range to start at a different number: Syntax: range(start, stop) Produces a sequence of integers from start to stop

Includes the start number (inclusive), does NOT include the stop number (exclusive) for i in range(3, 6): print(i) prints: 3 4 5 Runs for (stop start) iterations Variations on range What if we wrote range(1, 1)? It gives an empty sequence: stops before getting

to 1 The loop wont run at all! Loops can run for 0 iterations! Similarly, range(5, 1) is an empty sequence for i in range(5, 1): print(i) The body never executes (is dead code) Counting with steps The last variation on range: We can count by steps bigger than 1, only considering every nth number: Syntax: range(start, stop, step)

Instead of adding 1 in each iteration, adds step. The first number is still start The next number is start + step, then start + 2*step, Counting with steps What will this do? for i in range(10, 25, 5): print(i) Prints: 10 15 20

Does not include 25, the stop number is still exclusive. What about range(10, 2) ? # common error! Since there are only two arguments, it means start at 10 and stop at 2, NOT start at 0, stop at 10 and step 2! Counting backwards You can count down by providing a negative step. for i in range(3, 0, -1): print(Counting down:, i) print(Lift off!) Prints:

Counting down: 3 Counting down: 2 Counting down: 1 Lift off! The stop number is still exclusive! range(1, 5, -1) is an empty sequence Finding an average Suppose we have a collection of measurements in a list and we want to find their average: add them all up and divide by the number of measurements: temperatures = [67.0, 69.2, 55.3, 71.2, 65.4] We can get the number of measurements by a function called len:

len(temperatures) For the sum, we need some kind of a loop for temp in temperatures: We need to add another number in each iteration We need a variable to keep track of the sum We call such a variable an accumulator Accumulators are NOT new syntax Just a new way of using assignment A logical concept, used in most programming languages Accumulators

The general pattern of accumulators: Make an accumulator variable to hold the total Like the display on a calculator Before the loop starts, initialize the accumulator to a known value Like clearing out the calculator first If we are calculating a sum, start at 0 total = 0 0 is the identity for addition: adding 0 to a number doesnt change it Accumulators

Inside the loop, use assignment to update the accumulator for temp in temperatures: total = total + temp Or use augmented assignment: total += temp What if we dont initialize total first? NameError: defined name total is not

Accumulators Accumulators can be used for more than just adding bunches of numbers. Choose the initial value carefully so it doesnt change the result Factorial: 1, 2 = (1 x 2), 6 = (1 x 2 x 3), Inside the loop we will multiply the accumulator If we started the accumulator at zero, wed never get anything but zero! Accumulators The multiplicative identity is 1, use that. factorial = 1

for I in range (1, max + 1): factorial *= i Counting: how many times does something happen? Just like sum: initialize with zero. Instead of adding I, just add 1. numoff = 0 for i in range(1, 100, 2) numodd += 1 We call an accumulator like this a counter. More accumulators

Reversing a string Our accumulator will be a string Well loop over the characters of the input string Concatenate each new character to the beginning of the accumulator string What is the identity element for concatenation? (That is, what can you concatenate with, without changing the original string?) The empty string! Reversing a string instr = input(enter a string: ) reversed =

for char in instr: reversed = char + reversed print(instr,backwards is, reversed) See lecture8_examples at the course webpage for code examples.

Recently Viewed Presentations

  • SBAR Process - Quia

    SBAR Process - Quia

    SBAR PROCESS July 2012 SBAR HAND-OFF TRIAL The goal is to standardize the current hand-off process, housewide, and improve communication among all healthcare providers. WHY IS HAND-OFF SO IMPORTANT? JCAHO studies estimate that 80% of serious medical errors involve miscommunication...
  • Full-Day Kindergarten in the Hingham Public Schools

    Full-Day Kindergarten in the Hingham Public Schools

    Full-Day Kindergartenin the Hingham Public Schools. A Planning Update. January 29, 2015. ... and BOS to focus their discussions on FY 16 operating budget needs AND for parents to move forward with their planning for child placements for September 2015.
  • PowerPoint 簡報 - pudn.com

    PowerPoint 簡報 - pudn.com

    (Conceptual Application & Assessor Handbook) Presented by Rock Chang Country Manager Underwriters Laboratories Inc. (Taiwan) Issued: May 28, 2001 Revised: October 15, 2002 (簡) ...
  • Welcome to the MSc Organisational and Business Psychology

    Welcome to the MSc Organisational and Business Psychology

    Original Thinking Applied. MSc Organisational and Business Psychology. 2017/18. Welcome and congratulations! This is a prestigious programme and securing a place is not a given - we have turned away a number of strong students and the course was fully...
  • The Industry Bottle in Canada - Master Brewers Association of ...

    The Industry Bottle in Canada - Master Brewers Association of ...

    Ad hoc procedures for float allocation and replenishments. No objective process for resolving disputes. Increasing number of new brewers opting to introduce private mould floats . Violations in the standard float. ... The Industry Bottle in Canada
  • PURPOSE OF THE PRESENTATION  To demonstrate that there

    PURPOSE OF THE PRESENTATION To demonstrate that there

    in fact, a presentation like a powerpoint is really for the audience, and i am really tired of writing anything down right now. i imagine that most of you will probably have stopped reading this anyway. a presentation should include...
  • Case C-29/10 Heiko Koelzsch v. État du Grand-Duché de Luxembourg

    Case C-29/10 Heiko Koelzsch v. État du Grand-Duché de Luxembourg

    LEGAL CONTEXT: ARTICLE 6 ROME CONVENTION . INDIVIDUAL EMPLOYMENT CONTRACTS. Paragraph 1 - Notwithstanding the provisions of Article 3 (contract governed b the law chosen by the parties), in a contract of employment a choice of law made by the...
  • Chapter 21

    Chapter 21

    Tangency point - indifference curves. Marginal rates of substitution - same. Contract curve. Curve in Edgeworth box. All efficient trades. O G. O. E. The contract curve. The contract curve is a locus of all efficient trades, i.e., of all...