CS 115 Lecture 10 Structured programming; for loops Neil Moore - - PowerPoint PPT Presentation

cs 115 lecture 10
SMART_READER_LITE
LIVE PREVIEW

CS 115 Lecture 10 Structured programming; for loops Neil Moore - - PowerPoint PPT Presentation

CS 115 Lecture 10 Structured programming; for loops Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 October 2015 13 October 2015 The bad old days: GOTO In the early days of


slide-1
SLIDE 1

CS 115 Lecture 10

Structured programming; for loops Neil Moore

Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu

8 October 2015 13 October 2015

slide-2
SLIDE 2

The bad old days: GOTO

In the early days of programming, we didn’t have for loops, if statements, etc.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 2 / 31

slide-3
SLIDE 3

The bad old days: GOTO

In the early days of programming, we didn’t have for loops, if statements, etc. Instead, we had simply “if this is true, go to line 10”.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 2 / 31

slide-4
SLIDE 4

The bad old days: GOTO

In the early days of programming, we didn’t have for loops, if statements, etc. Instead, we had simply “if this is true, go to line 10”. Could use that to skip over code (like an if).

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 2 / 31

slide-5
SLIDE 5

The bad old days: GOTO

In the early days of programming, we didn’t have for loops, if statements, etc. Instead, we had simply “if this is true, go to line 10”. Could use that to skip over code (like an if). . . . or go to an earlier line to write a loop.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 2 / 31

slide-6
SLIDE 6

The bad old days: GOTO

In the early days of programming, we didn’t have for loops, if statements, etc. Instead, we had simply “if this is true, go to line 10”. Could use that to skip over code (like an if). . . . or go to an earlier line to write a loop. This was very tedious and error prone.

◮ . . . especially if something has to be changed. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 2 / 31

slide-7
SLIDE 7

The bad old days: GOTO

In the early days of programming, we didn’t have for loops, if statements, etc. Instead, we had simply “if this is true, go to line 10”. Could use that to skip over code (like an if). . . . or go to an earlier line to write a loop. This was very tedious and error prone.

◮ . . . especially if something has to be changed. ◮ “Spaghetti code”: trying to trace a program was like trying to trace

  • ne strand in a plate of spaghetti.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 2 / 31

slide-8
SLIDE 8

The bad old days: GOTO

In the early days of programming, we didn’t have for loops, if statements, etc. Instead, we had simply “if this is true, go to line 10”. Could use that to skip over code (like an if). . . . or go to an earlier line to write a loop. This was very tedious and error prone.

◮ . . . especially if something has to be changed. ◮ “Spaghetti code”: trying to trace a program was like trying to trace

  • ne strand in a plate of spaghetti.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 2 / 31

slide-9
SLIDE 9

Structured programming

In the 1960s, computer scientists started to think about how to write programs that were easier to understand and follow.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 3 / 31

slide-10
SLIDE 10

Structured programming

In the 1960s, computer scientists started to think about how to write programs that were easier to understand and follow.

◮ Edsger Dijkstra, “Go To Statement Considered Harmful” (1968). Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 3 / 31

slide-11
SLIDE 11

Structured programming

In the 1960s, computer scientists started to think about how to write programs that were easier to understand and follow.

◮ Edsger Dijkstra, “Go To Statement Considered Harmful” (1968).

They introduced the paradigm of structured programming.

◮ Patterns that lead to easier-to-understand programs. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 3 / 31

slide-12
SLIDE 12

Structured programming

In the 1960s, computer scientists started to think about how to write programs that were easier to understand and follow.

◮ Edsger Dijkstra, “Go To Statement Considered Harmful” (1968).

They introduced the paradigm of structured programming.

◮ Patterns that lead to easier-to-understand programs. ⋆ Easier to test and debug. ⋆ Easier to modify and maintain. ⋆ Easier to collaborate on large programs. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 3 / 31

slide-13
SLIDE 13

Structured programming

In the 1960s, computer scientists started to think about how to write programs that were easier to understand and follow.

◮ Edsger Dijkstra, “Go To Statement Considered Harmful” (1968).

They introduced the paradigm of structured programming.

◮ Patterns that lead to easier-to-understand programs. ⋆ Easier to test and debug. ⋆ Easier to modify and maintain. ⋆ Easier to collaborate on large programs. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 3 / 31

slide-14
SLIDE 14

Data structures and control structures

We’ve already seen a little about data structures:

◮ Ways of organizing data within a program. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 4 / 31

slide-15
SLIDE 15

Data structures and control structures

We’ve already seen a little about data structures:

◮ Ways of organizing data within a program. ⋆ (Remember, in the computer it’s all binary) Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 4 / 31

slide-16
SLIDE 16

Data structures and control structures

We’ve already seen a little about data structures:

◮ Ways of organizing data within a program. ⋆ (Remember, in the computer it’s all binary) ◮ Simple: Constants, variables. ◮ More complex: Graphics objects, strings, lists. . . Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 4 / 31

slide-17
SLIDE 17

Data structures and control structures

We’ve already seen a little about data structures:

◮ Ways of organizing data within a program. ⋆ (Remember, in the computer it’s all binary) ◮ Simple: Constants, 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. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 4 / 31

slide-18
SLIDE 18

Data structures and control structures

We’ve already seen a little about data structures:

◮ Ways of organizing data within a program. ⋆ (Remember, in the computer it’s all binary) ◮ Simple: Constants, 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. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 4 / 31

slide-19
SLIDE 19

The three basic control structures

In 1966, B¨

  • hm and Jacopini showed that any program using “go to” could

be rearranged to use only three simple control structures. Sequence. Selection. Iteration.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 5 / 31

slide-20
SLIDE 20

The three basic control structures

In 1966, B¨

  • hm and Jacopini showed that any program using “go to” could

be rearranged to use only three simple control structures. Sequence. Selection. Iteration. We’ll add a fourth: Subprograms (more in chapter 5).

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 5 / 31

slide-21
SLIDE 21

The three basic control structures

In 1966, B¨

  • hm and Jacopini showed that any program using “go to” could

be rearranged to use only three simple control structures. Sequence. Selection. Iteration. We’ll add a fourth: 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 leave the control structure.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 5 / 31

slide-22
SLIDE 22

The three basic control structures

In 1966, B¨

  • hm and Jacopini showed that any program using “go to” could

be rearranged to use only three simple control structures. Sequence. Selection. Iteration. We’ll add a fourth: 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 leave the control structure. One entrance, one exit.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 5 / 31

slide-23
SLIDE 23

The three basic control structures

In 1966, B¨

  • hm and Jacopini showed that any program using “go to” could

be rearranged to use only three simple control structures. Sequence. Selection. Iteration. We’ll add a fourth: 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 leave the control structure. One entrance, one exit.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 5 / 31

slide-24
SLIDE 24

Sequence

“Sequencing” or “sequential execution” just means: Running one statement after another. In Python we just write one line after the next. “The default” in some sense.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 6 / 31

slide-25
SLIDE 25

Sequence

“Sequencing” or “sequential execution” just means: Running one statement after another. In Python we just write one line after the next. “The default” in some sense. Guarantees:

◮ The steps will execute in the order given. ◮ Steps will not be skipped. ◮ Will always start at the first statement of the sequence. . . ◮ and finish at the last statement. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 6 / 31

slide-26
SLIDE 26

Sequence

“Sequencing” or “sequential execution” just means: Running one statement after another. In Python we just write one line after the next. “The default” in some sense. Guarantees:

◮ The steps will execute in the order given. ◮ Steps will not be skipped. ◮ Will always start at the first statement of the sequence. . . ◮ and finish at the last statement. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 6 / 31

slide-27
SLIDE 27

Selection

“Selection” means choosing which code to run based on some condition or question. In Python, an if-else statement.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 7 / 31

slide-28
SLIDE 28

Selection

“Selection” means choosing which code to run based on some condition or question. In Python, an if-else statement. Two branches: true and false.

◮ Each branch is another control structure (most often a sequence). Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 7 / 31

slide-29
SLIDE 29

Selection

“Selection” means choosing which code to run based on some condition or question. In Python, an if-else statement. Two branches: true and false.

◮ Each branch is another control structure (most often a sequence).

Guarantees:

◮ Always starts with the question/condition. ◮ Runs one branch or the other, never both. ◮ . . . and never neither. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 7 / 31

slide-30
SLIDE 30

Selection

“Selection” means choosing which code to run based on some condition or question. In Python, an if-else statement. Two branches: true and false.

◮ Each branch is another control structure (most often a sequence).

Guarantees:

◮ Always starts with the question/condition. ◮ Runs one branch or the other, never both. ◮ . . . and never neither.

Avoid dead code: code that is never executed.

◮ Often because the condition is always true or always false. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 7 / 31

slide-31
SLIDE 31

Selection

“Selection” means choosing which code to run based on some condition or question. In Python, an if-else statement. Two branches: true and false.

◮ Each branch is another control structure (most often a sequence).

Guarantees:

◮ Always starts with the question/condition. ◮ Runs one branch or the other, never both. ◮ . . . and never neither.

Avoid dead code: code that is never executed.

◮ Often because the condition is always true or always false. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 7 / 31

slide-32
SLIDE 32

Iteration

“Iteration” means running code multiple times (a loop). In structured programming, “repeat this body until a condition is false”. In Python, a while loop (in about a week).

◮ for loops are a special case of iteration. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 8 / 31

slide-33
SLIDE 33

Iteration

“Iteration” means running code multiple times (a loop). In structured programming, “repeat this body until a condition is false”. In Python, a while loop (in about a week).

◮ 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.

◮ Otherwise (the condition is false), leaves the loop. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 8 / 31

slide-34
SLIDE 34

Iteration

“Iteration” means running code multiple times (a loop). In structured programming, “repeat this body until a condition is false”. In Python, a while loop (in about a week).

◮ 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.

◮ Otherwise (the condition is false), leaves the loop.

Be careful to avoid infinite loops, where the condition is always true.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 8 / 31

slide-35
SLIDE 35

Iteration

“Iteration” means running code multiple times (a loop). In structured programming, “repeat this body until a condition is false”. In Python, a while loop (in about a week).

◮ 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.

◮ Otherwise (the condition is false), leaves the loop.

Be careful to avoid infinite loops, where the condition is always true.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 8 / 31

slide-36
SLIDE 36

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-37
SLIDE 37

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times. A subprogram is a chunk of the flowchart treated as a single unit.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-38
SLIDE 38

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times. A subprogram is a chunk of the flowchart treated as a single unit. When we need to execute those steps, we call the subprogram.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-39
SLIDE 39

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times. A subprogram is a chunk of the flowchart treated as a single unit. When we need to execute those steps, we call the subprogram.

◮ Run the subprogram, wait for it to finish. ◮ Keep going where you left off. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-40
SLIDE 40

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times. A subprogram is a chunk of the flowchart treated as a single unit. When we need to execute those steps, we call the subprogram.

◮ Run the subprogram, wait for it to finish. ◮ Keep going where you left off. ◮ Sometimes we send values to the subprogram. ◮ And sometimes the subprogram sends a value back. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-41
SLIDE 41

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times. A subprogram is a chunk of the flowchart treated as a single unit. When we need to execute those steps, we call the subprogram.

◮ Run the subprogram, wait for it to finish. ◮ Keep going where you left off. ◮ Sometimes we send values to the subprogram. ◮ And sometimes the subprogram sends a value back.

In Python, subprograms are called functions.

◮ Arguments are the values we send to the subprogram. ◮ And the function can return a result. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-42
SLIDE 42

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times. A subprogram is a chunk of the flowchart treated as a single unit. When we need to execute those steps, we call the subprogram.

◮ Run the subprogram, wait for it to finish. ◮ Keep going where you left off. ◮ Sometimes we send values to the subprogram. ◮ And sometimes the subprogram sends a value back.

In Python, subprograms are called functions.

◮ Arguments are the values we send to the subprogram. ◮ And the function can return a result. ◮ Can you think of Python functions that: ⋆ Take one or more arguments? Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-43
SLIDE 43

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times. A subprogram is a chunk of the flowchart treated as a single unit. When we need to execute those steps, we call the subprogram.

◮ Run the subprogram, wait for it to finish. ◮ Keep going where you left off. ◮ Sometimes we send values to the subprogram. ◮ And sometimes the subprogram sends a value back.

In Python, subprograms are called functions.

◮ Arguments are the values we send to the subprogram. ◮ And the function can return a result. ◮ Can you think of Python functions that: ⋆ Take one or more arguments? ⋆ Take no arguments? Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-44
SLIDE 44

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times. A subprogram is a chunk of the flowchart treated as a single unit. When we need to execute those steps, we call the subprogram.

◮ Run the subprogram, wait for it to finish. ◮ Keep going where you left off. ◮ Sometimes we send values to the subprogram. ◮ And sometimes the subprogram sends a value back.

In Python, subprograms are called functions.

◮ Arguments are the values we send to the subprogram. ◮ And the function can return a result. ◮ Can you think of Python functions that: ⋆ Take one or more arguments? ⋆ Take no arguments? ⋆ Return a result? Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-45
SLIDE 45

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times. A subprogram is a chunk of the flowchart treated as a single unit. When we need to execute those steps, we call the subprogram.

◮ Run the subprogram, wait for it to finish. ◮ Keep going where you left off. ◮ Sometimes we send values to the subprogram. ◮ And sometimes the subprogram sends a value back.

In Python, subprograms are called functions.

◮ Arguments are the values we send to the subprogram. ◮ And the function can return a result. ◮ Can you think of Python functions that: ⋆ Take one or more arguments? ⋆ Take no arguments? ⋆ Return a result? ⋆ Don’t return a result? Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-46
SLIDE 46

Subprograms

Sometimes we may need to repeat the same combination of control structures in several different places. It would be nice if we didn’t have to write the code multiple times. A subprogram is a chunk of the flowchart treated as a single unit. When we need to execute those steps, we call the subprogram.

◮ Run the subprogram, wait for it to finish. ◮ Keep going where you left off. ◮ Sometimes we send values to the subprogram. ◮ And sometimes the subprogram sends a value back.

In Python, subprograms are called functions.

◮ Arguments are the values we send to the subprogram. ◮ And the function can return a result. ◮ Can you think of Python functions that: ⋆ Take one or more arguments? ⋆ Take no arguments? ⋆ Return a result? ⋆ Don’t return a result? Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 9 / 31

slide-47
SLIDE 47

Control structures summary

Sequence (one statement after the other: easy to forget) Selection (conditionals: if) Iteration (loops: for and while) Subprograms (functions: def)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 10 / 31

slide-48
SLIDE 48

Control structures summary

Sequence (one statement after the other: easy to forget) Selection (conditionals: if) Iteration (loops: for and while) Subprograms (functions: def)

We’ve seen sequence and selection already, so now let’s look at iteration in more detail.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 10 / 31

slide-49
SLIDE 49

Control structures summary

Sequence (one statement after the other: easy to forget) Selection (conditionals: if) Iteration (loops: for and while) Subprograms (functions: def)

We’ve seen sequence and selection already, so now let’s look at iteration in more detail.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 10 / 31

slide-50
SLIDE 50

Repeating yourself

What if we wanted to draw a tic-tac-toe board with 4 × 4 lines? We could write code to draw a vertical line. . . . . . and code to draw a horizontal line. . .

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 11 / 31

slide-51
SLIDE 51

Repeating yourself

What if we wanted to draw a tic-tac-toe board with 4 × 4 lines? We could write code to draw a vertical line. . . . . . and code to draw a horizontal line. . . We need to do that four times each.

◮ With different coordinates each time.

Do we have to copy-and-paste each one 4 times?

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 11 / 31

slide-52
SLIDE 52

Repeating yourself

What if we wanted to draw a tic-tac-toe board with 4 × 4 lines? We could write code to draw a vertical line. . . . . . and code to draw a horizontal line. . . We need to do that four times each.

◮ With different coordinates each time.

Do we have to copy-and-paste each one 4 times?

◮ Of course not! ◮ Loops allow you to execute code multiple times.

. . . with a variable that is different each time.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 11 / 31

slide-53
SLIDE 53

Repeating yourself

What if we wanted to draw a tic-tac-toe board with 4 × 4 lines? We could write code to draw a vertical line. . . . . . and code to draw a horizontal line. . . We need to do that four times each.

◮ With different coordinates each time.

Do we have to copy-and-paste each one 4 times?

◮ Of course not! ◮ Loops allow you to execute code multiple times.

. . . with a variable that is different each time.

Two kinds of loop: definite and indefinite.

◮ Definite loops know in advance how many times to run. ◮ Indefinite loops run until some condition is satisfied. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 11 / 31

slide-54
SLIDE 54

Repeating yourself

What if we wanted to draw a tic-tac-toe board with 4 × 4 lines? We could write code to draw a vertical line. . . . . . and code to draw a horizontal line. . . We need to do that four times each.

◮ With different coordinates each time.

Do we have to copy-and-paste each one 4 times?

◮ Of course not! ◮ Loops allow you to execute code multiple times.

. . . with a variable that is different each time.

Two kinds of loop: definite and indefinite.

◮ Definite loops know in advance how many times to run. ◮ Indefinite loops run until some condition is satisfied. ◮ Today we’ll see how to write definite loops in Python. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 11 / 31

slide-55
SLIDE 55

Repeating yourself

What if we wanted to draw a tic-tac-toe board with 4 × 4 lines? We could write code to draw a vertical line. . . . . . and code to draw a horizontal line. . . We need to do that four times each.

◮ With different coordinates each time.

Do we have to copy-and-paste each one 4 times?

◮ Of course not! ◮ Loops allow you to execute code multiple times.

. . . with a variable that is different each time.

Two kinds of loop: definite and indefinite.

◮ Definite loops know in advance how many times to run. ◮ Indefinite loops run until some condition is satisfied. ◮ Today we’ll see how to write definite loops in Python. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 11 / 31

slide-56
SLIDE 56

The for loop

Syntax: for var in sequence :

◮ Followed by a block (collection of indented lines) called the body. ⋆ The body must be indented past the “for”! ◮ var is an identifier (variable name). Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 12 / 31

slide-57
SLIDE 57

The for loop

Syntax: for var in sequence :

◮ Followed by a block (collection of indented lines) called the body. ⋆ The body must be indented past the “for”! ◮ 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. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 12 / 31

slide-58
SLIDE 58

The for loop

Syntax: for var in sequence :

◮ Followed by a block (collection of indented lines) called the body. ⋆ The body must be indented past the “for”! ◮ 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.

A very simple for loop: for color in (’red’, ’green’, ’blue’): print(color, ’is a primary color.’)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 12 / 31

slide-59
SLIDE 59

The for loop

Syntax: for var in sequence :

◮ Followed by a block (collection of indented lines) called the body. ⋆ The body must be indented past the “for”! ◮ 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.

A very simple for loop: for color in (’red’, ’green’, ’blue’): print(color, ’is a primary color.’) We’re giving a tuple, but a list in square brackets would work too.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 12 / 31

slide-60
SLIDE 60

The for loop

Syntax: for var in sequence :

◮ Followed by a block (collection of indented lines) called the body. ⋆ The body must be indented past the “for”! ◮ 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.

A very simple for loop: for color in (’red’, ’green’, ’blue’): print(color, ’is a primary color.’) We’re giving a tuple, but a list in square brackets would work too. When executed it does: Iteration 1: print(’red’, ’is a primary color.’)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 12 / 31

slide-61
SLIDE 61

The for loop

Syntax: for var in sequence :

◮ Followed by a block (collection of indented lines) called the body. ⋆ The body must be indented past the “for”! ◮ 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.

A very simple for loop: for color in (’red’, ’green’, ’blue’): print(color, ’is a primary color.’) We’re giving a tuple, but a list in square brackets would work too. When executed it does: Iteration 1: print(’red’, ’is a primary color.’) Iteration 2: print(’green’, ’is a primary color.’)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 12 / 31

slide-62
SLIDE 62

The for loop

Syntax: for var in sequence :

◮ Followed by a block (collection of indented lines) called the body. ⋆ The body must be indented past the “for”! ◮ 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.

A very simple for loop: for color in (’red’, ’green’, ’blue’): print(color, ’is a primary color.’) We’re giving a tuple, but a list in square brackets would work too. When executed it does: Iteration 1: print(’red’, ’is a primary color.’) Iteration 2: print(’green’, ’is a primary color.’) Iteration 3: print(’blue’, ’is a primary color.’)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 12 / 31

slide-63
SLIDE 63

The for loop

Syntax: for var in sequence :

◮ Followed by a block (collection of indented lines) called the body. ⋆ The body must be indented past the “for”! ◮ 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.

A very simple for loop: for color in (’red’, ’green’, ’blue’): print(color, ’is a primary color.’) We’re giving a tuple, but a list in square brackets would work too. When executed it does: Iteration 1: print(’red’, ’is a primary color.’) Iteration 2: print(’green’, ’is a primary color.’) Iteration 3: print(’blue’, ’is a primary color.’)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 12 / 31

slide-64
SLIDE 64

Other kinds of sequences

Strings can also be used as sequences. Each iteration of the loop operates

  • n a single character:

name = input("What is your name? ") for char in name: print(char)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 13 / 31

slide-65
SLIDE 65

Other kinds of sequences

Strings can also be used as sequences. Each iteration of the loop operates

  • n a single character:

name = input("What is your name? ") for char in name: print(char) Prints this: M

  • r

e

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 13 / 31

slide-66
SLIDE 66

Other kinds of sequences

Strings can also be used as sequences. Each iteration of the loop operates

  • n a single character:

name = input("What is your name? ") for char in name: print(char) Prints this: M

  • r

e

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 13 / 31

slide-67
SLIDE 67

Numeric ranges

One of the most common, and most useful, kinds of sequence for a for loop is a numeric range.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 14 / 31

slide-68
SLIDE 68

Numeric ranges

One of the most common, and most useful, kinds of sequence for a for loop is a numeric range. In Python, you create numeric ranges with the range function. There are three ways to call range:

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 14 / 31

slide-69
SLIDE 69

Numeric ranges

One of the most common, and most useful, kinds of sequence for a for loop is a numeric range. In Python, you create numeric ranges with the range function. There are three ways to call range: range(3): counts from 0 up to 2.

◮ Computer scientists usually count from zero, not one. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 14 / 31

slide-70
SLIDE 70

Numeric ranges

One of the most common, and most useful, kinds of sequence for a for loop is a numeric range. In Python, you create numeric ranges with the range function. 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 number.

(just like randrange!)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 14 / 31

slide-71
SLIDE 71

Numeric ranges

One of the most common, and most useful, kinds of sequence for a for loop is a numeric range. In Python, you create numeric ranges with the range function. 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 number.

(just like randrange!) for i in range(3): print(i, "squared is", i**2)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 14 / 31

slide-72
SLIDE 72

Numeric ranges

One of the most common, and most useful, kinds of sequence for a for loop is a numeric range. In Python, you create numeric ranges with the range function. 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 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 4

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 14 / 31

slide-73
SLIDE 73

Numeric ranges

One of the most common, and most useful, kinds of sequence for a for loop is a numeric range. In Python, you create numeric ranges with the range function. 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 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 4

◮ Notice the loop ran 3 times (0, 1, 2). ⋆ Don’t make a fencepost error! Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 14 / 31

slide-74
SLIDE 74

Numeric ranges

One of the most common, and most useful, kinds of sequence for a for loop is a numeric range. In Python, you create numeric ranges with the range function. 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 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 4

◮ Notice the loop ran 3 times (0, 1, 2). ⋆ Don’t make a fencepost error! Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 14 / 31

slide-75
SLIDE 75

More ranges

We can also tell range to start at a different number: Syntax: range(start, stop)

◮ Produces a sequence of integers from start to stop. ◮ Does include the start (inclusive), not the stop (exclusive). Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 15 / 31

slide-76
SLIDE 76

More ranges

We can also tell range to start at a different number: Syntax: range(start, stop)

◮ Produces a sequence of integers from start to stop. ◮ Does include the start (inclusive), not the stop (exclusive).

for i in range(3, 6): print(i)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 15 / 31

slide-77
SLIDE 77

More ranges

We can also tell range to start at a different number: Syntax: range(start, stop)

◮ Produces a sequence of integers from start to stop. ◮ Does include the start (inclusive), not the stop (exclusive).

for i in range(3, 6): print(i) Prints: 3 4 5

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 15 / 31

slide-78
SLIDE 78

More ranges

We can also tell range to start at a different number: Syntax: range(start, stop)

◮ Produces a sequence of integers from start to stop. ◮ Does include the start (inclusive), not the stop (exclusive).

for i in range(3, 6): print(i) Prints: 3 4 5

◮ Runs for (stop - start) iterations. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 15 / 31

slide-79
SLIDE 79

More ranges

We can also tell range to start at a different number: Syntax: range(start, stop)

◮ Produces a sequence of integers from start to stop. ◮ Does include the start (inclusive), not the stop (exclusive).

for i in range(3, 6): print(i) Prints: 3 4 5

◮ Runs for (stop - start) iterations.

What if we wrote range(1, 1)?

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 15 / 31

slide-80
SLIDE 80

More ranges

We can also tell range to start at a different number: Syntax: range(start, stop)

◮ Produces a sequence of integers from start to stop. ◮ Does include the start (inclusive), not the stop (exclusive).

for i in range(3, 6): print(i) Prints: 3 4 5

◮ Runs for (stop - start) iterations.

What if we wrote range(1, 1)?

◮ Empty sequence: stops before getting to 1. ◮ The loop wouldn’t run at all! Loops can run for 0 iterations. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 15 / 31

slide-81
SLIDE 81

More ranges

We can also tell range to start at a different number: Syntax: range(start, stop)

◮ Produces a sequence of integers from start to stop. ◮ Does include the start (inclusive), not the stop (exclusive).

for i in range(3, 6): print(i) Prints: 3 4 5

◮ Runs for (stop - start) iterations.

What if we wrote range(1, 1)?

◮ Empty sequence: stops before getting to 1. ◮ The loop wouldn’t run at all! Loops can run for 0 iterations. ◮ Similarly, range(5, 1) is an empty sequence. ⋆ So this loop will do nothing:

for i in range(1, 5, -1): print(i)

⋆ The body never executes (is dead code). Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 15 / 31

slide-82
SLIDE 82

More ranges

We can also tell range to start at a different number: Syntax: range(start, stop)

◮ Produces a sequence of integers from start to stop. ◮ Does include the start (inclusive), not the stop (exclusive).

for i in range(3, 6): print(i) Prints: 3 4 5

◮ Runs for (stop - start) iterations.

What if we wrote range(1, 1)?

◮ Empty sequence: stops before getting to 1. ◮ The loop wouldn’t run at all! Loops can run for 0 iterations. ◮ Similarly, range(5, 1) is an empty sequence. ⋆ So this loop will do nothing:

for i in range(1, 5, -1): print(i)

⋆ The body never executes (is dead code). Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 15 / 31

slide-83
SLIDE 83

Counting with steps

Finally, we can tell range to count by steps, 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, . . . ◮ What will this do?

for i in range(10, 25, 5): print(i)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 16 / 31

slide-84
SLIDE 84

Counting with steps

Finally, we can tell range to count by steps, 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, . . . ◮ What will this do?

for i in range(10, 25, 5): print(i)

◮ Prints:

10

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 16 / 31

slide-85
SLIDE 85

Counting with steps

Finally, we can tell range to count by steps, 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, . . . ◮ What will this do?

for i in range(10, 25, 5): print(i)

◮ Prints:

10 15

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 16 / 31

slide-86
SLIDE 86

Counting with steps

Finally, we can tell range to count by steps, 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, . . . ◮ What will this do?

for i in range(10, 25, 5): print(i)

◮ Prints:

10 15 20

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 16 / 31

slide-87
SLIDE 87

Counting with steps

Finally, we can tell range to count by steps, 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, . . . ◮ What will this do?

for i in range(10, 25, 5): print(i)

◮ Prints:

10 15 20

◮ Does not include 25: stop is still exclusive. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 16 / 31

slide-88
SLIDE 88

Counting with steps

Finally, we can tell range to count by steps, 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, . . . ◮ What will this do?

for i in range(10, 25, 5): print(i)

◮ Prints:

10 15 20

◮ Does not include 25: stop is still exclusive.

What about range(10, 2)?

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 16 / 31

slide-89
SLIDE 89

Counting with steps

Finally, we can tell range to count by steps, 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, . . . ◮ What will this do?

for i in range(10, 25, 5): print(i)

◮ Prints:

10 15 20

◮ Does not include 25: stop is still exclusive.

What about range(10, 2)?

◮ Two arguments are start and stop, not step. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 16 / 31

slide-90
SLIDE 90

Counting with steps

Finally, we can tell range to count by steps, 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, . . . ◮ What will this do?

for i in range(10, 25, 5): print(i)

◮ Prints:

10 15 20

◮ Does not include 25: stop is still exclusive.

What about range(10, 2)?

◮ Two arguments are start and stop, not step. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 16 / 31

slide-91
SLIDE 91

Counting backwards

You can count down by providing a negative step. for i in range(3, 0, -1): print("Counting down:", i)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 17 / 31

slide-92
SLIDE 92

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!")

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 17 / 31

slide-93
SLIDE 93

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

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 17 / 31

slide-94
SLIDE 94

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

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 17 / 31

slide-95
SLIDE 95

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

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 17 / 31

slide-96
SLIDE 96

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 is still exclusive.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 17 / 31

slide-97
SLIDE 97

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 is still exclusive. range(1, 5, -1) is an empty sequence.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 17 / 31

slide-98
SLIDE 98

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 is still exclusive. range(1, 5, -1) is an empty sequence.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 17 / 31

slide-99
SLIDE 99

Tic-tac-toe grid

Now we can make that tic-tac-toe grid. We’ll have one loop to draw the vertical lines. And another to draw the horizontal lines. grid.py

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 18 / 31

slide-100
SLIDE 100

Tic-tac-toe grid

Now we can make that tic-tac-toe grid. We’ll have one loop to draw the vertical lines. And another to draw the horizontal lines. grid.py A neat “display hack” (simple code to make an intricate picture) using for loops and if: moire.py

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 18 / 31

slide-101
SLIDE 101

Tic-tac-toe grid

Now we can make that tic-tac-toe grid. We’ll have one loop to draw the vertical lines. And another to draw the horizontal lines. grid.py A neat “display hack” (simple code to make an intricate picture) using for loops and if: moire.py

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 18 / 31

slide-102
SLIDE 102

Averages

Suppose we have a collections 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]

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 19 / 31

slide-103
SLIDE 103

Averages

Suppose we have a collections 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 length with len(temperatures) For the sum, we need some kind of loop. for temp in temperatures:

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 19 / 31

slide-104
SLIDE 104

Averages

Suppose we have a collections 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 length with len(temperatures) For the sum, we need some kind of loop. for temp in temperatures: We’d need to add the next number in each iteration.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 19 / 31

slide-105
SLIDE 105

Averages

Suppose we have a collections 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 length with len(temperatures) For the sum, we need some kind of loop. for temp in temperatures: We’d need to add the next number in each iteration. We need a variable to keep track of the sum.

◮ We call such a variable an accumulator. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 19 / 31

slide-106
SLIDE 106

Averages

Suppose we have a collections 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 length with len(temperatures) For the sum, we need some kind of loop. for temp in temperatures: We’d need to add the next number in each iteration. We need a variable to keep track of the sum.

◮ We call such a variable an accumulator.

Accumulators aren’t new syntax.

◮ Just a new way of using assignment. ◮ A logical concept, used in most programming languages. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 19 / 31

slide-107
SLIDE 107

Averages

Suppose we have a collections 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 length with len(temperatures) For the sum, we need some kind of loop. for temp in temperatures: We’d need to add the next number in each iteration. We need a variable to keep track of the sum.

◮ We call such a variable an accumulator.

Accumulators aren’t new syntax.

◮ Just a new way of using assignment. ◮ A logical concept, used in most programming languages. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 19 / 31

slide-108
SLIDE 108

Accumulators

The general idea of accumulators: Make an accumulator variable to hold the “total”.

◮ Like the display on a calculator. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 20 / 31

slide-109
SLIDE 109

Accumulators

The general idea of accumulators: Make an accumulator variable to hold the “total”.

◮ Like the display on a calculator.

Before the loop, initialize it to a known value.

◮ Clear the calculator first! ◮ If we are calculating a sum, start at 0.

total = 0

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 20 / 31

slide-110
SLIDE 110

Accumulators

The general idea of accumulators: Make an accumulator variable to hold the “total”.

◮ Like the display on a calculator.

Before the loop, initialize it to a known value.

◮ Clear 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 doesn’t change it. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 20 / 31

slide-111
SLIDE 111

Accumulators

The general idea of accumulators: Make an accumulator variable to hold the “total”.

◮ Like the display on a calculator.

Before the loop, initialize it to a known value.

◮ Clear 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 doesn’t change it.

Inside the loop, use assignment to update the accumulator.

for temp in temperatures: total = total + temp

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 20 / 31

slide-112
SLIDE 112

Accumulators

The general idea of accumulators: Make an accumulator variable to hold the “total”.

◮ Like the display on a calculator.

Before the loop, initialize it to a known value.

◮ Clear 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 doesn’t change it.

Inside the loop, use assignment to update the accumulator.

for temp in temperatures: total = total + temp

◮ Or use augmented assignment:

total += temp

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 20 / 31

slide-113
SLIDE 113

Accumulators

The general idea of accumulators: Make an accumulator variable to hold the “total”.

◮ Like the display on a calculator.

Before the loop, initialize it to a known value.

◮ Clear 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 doesn’t change it.

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 didn’t initialize total first?

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 20 / 31

slide-114
SLIDE 114

Accumulators

The general idea of accumulators: Make an accumulator variable to hold the “total”.

◮ Like the display on a calculator.

Before the loop, initialize it to a known value.

◮ Clear 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 doesn’t change it.

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 didn’t initialize total first?

◮ NameError:

name ’total’ is not defined

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 20 / 31

slide-115
SLIDE 115

Accumulators

The general idea of accumulators: Make an accumulator variable to hold the “total”.

◮ Like the display on a calculator.

Before the loop, initialize it to a known value.

◮ Clear 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 doesn’t change it.

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 didn’t initialize total first?

◮ NameError:

name ’total’ is not defined

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 20 / 31

slide-116
SLIDE 116

Accumulators

Accumulators can be used for more than just addition. Choose the initial value carefully so it doesn’t change the result.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 21 / 31

slide-117
SLIDE 117

Accumulators

Accumulators can be used for more than just addition. Choose the initial value carefully so it doesn’t change the result. Factorial: 1, 2 = (1 × 2), 6 = (1 × 2 × 3), . . .

◮ Inside the loop we will multiply the accumulator. ◮ If we started with 0, we’d never get anything but 0. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 21 / 31

slide-118
SLIDE 118

Accumulators

Accumulators can be used for more than just addition. Choose the initial value carefully so it doesn’t change the result. Factorial: 1, 2 = (1 × 2), 6 = (1 × 2 × 3), . . .

◮ Inside the loop we will multiply the accumulator. ◮ If we started with 0, we’d never get anything but 0. ◮ The multiplicative identity is 1: use that.

factorial = 1 for i in range(1, max + 1): factorial *= i

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 21 / 31

slide-119
SLIDE 119

Accumulators

Accumulators can be used for more than just addition. Choose the initial value carefully so it doesn’t change the result. Factorial: 1, 2 = (1 × 2), 6 = (1 × 2 × 3), . . .

◮ Inside the loop we will multiply the accumulator. ◮ If we started with 0, we’d never get anything but 0. ◮ 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 0. ◮ Instead of adding i, just add 1.

numodd = 0 for i in range(1, 100, 2): numodd += 1

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 21 / 31

slide-120
SLIDE 120

Accumulators

Accumulators can be used for more than just addition. Choose the initial value carefully so it doesn’t change the result. Factorial: 1, 2 = (1 × 2), 6 = (1 × 2 × 3), . . .

◮ Inside the loop we will multiply the accumulator. ◮ If we started with 0, we’d never get anything but 0. ◮ 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 0. ◮ Instead of adding i, just add 1.

numodd = 0 for i in range(1, 100, 2): numodd += 1

◮ We call an accumulator like this a counter. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 21 / 31

slide-121
SLIDE 121

Accumulators

Accumulators can be used for more than just addition. Choose the initial value carefully so it doesn’t change the result. Factorial: 1, 2 = (1 × 2), 6 = (1 × 2 × 3), . . .

◮ Inside the loop we will multiply the accumulator. ◮ If we started with 0, we’d never get anything but 0. ◮ 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 0. ◮ Instead of adding i, just add 1.

numodd = 0 for i in range(1, 100, 2): numodd += 1

◮ We call an accumulator like this a counter. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 21 / 31

slide-122
SLIDE 122

More accumulators

Reversing a string.

◮ Our accumulator will be a string. ◮ We’ll loop over the characters of the input string. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 22 / 31

slide-123
SLIDE 123

More accumulators

Reversing a string.

◮ Our accumulator will be a string. ◮ We’ll loop over the characters of the input string. ◮ Concatenate each new character to the beginning of the accumulator. ⋆ What is the identity for concatenation? ⋆ (What can you concatenate with without changing the answer?) Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 22 / 31

slide-124
SLIDE 124

More accumulators

Reversing a string.

◮ Our accumulator will be a string. ◮ We’ll loop over the characters of the input string. ◮ Concatenate each new character to the beginning of the accumulator. ⋆ What is the identity for concatenation? ⋆ (What can you concatenate with without changing the answer?) ⋆ The empty string!

instr = input("Enter a string: ") reversed = ""

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 22 / 31

slide-125
SLIDE 125

More accumulators

Reversing a string.

◮ Our accumulator will be a string. ◮ We’ll loop over the characters of the input string. ◮ Concatenate each new character to the beginning of the accumulator. ⋆ What is the identity for concatenation? ⋆ (What can you concatenate with without changing the answer?) ⋆ The empty string!

instr = input("Enter a string: ") reversed = "" for char in instr:

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 22 / 31

slide-126
SLIDE 126

More accumulators

Reversing a string.

◮ Our accumulator will be a string. ◮ We’ll loop over the characters of the input string. ◮ Concatenate each new character to the beginning of the accumulator. ⋆ What is the identity for concatenation? ⋆ (What can you concatenate with without changing the answer?) ⋆ The empty string!

instr = input("Enter a string: ") reversed = "" for char in instr: reversed = char + reversed

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 22 / 31

slide-127
SLIDE 127

More accumulators

Reversing a string.

◮ Our accumulator will be a string. ◮ We’ll loop over the characters of the input string. ◮ Concatenate each new character to the beginning of the accumulator. ⋆ What is the identity for concatenation? ⋆ (What can you concatenate with without changing the answer?) ⋆ The empty string!

instr = input("Enter a string: ") reversed = "" for char in instr: reversed = char + reversed print(instr, "backwards is", reversed)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 22 / 31

slide-128
SLIDE 128

More accumulators

Reversing a string.

◮ Our accumulator will be a string. ◮ We’ll loop over the characters of the input string. ◮ Concatenate each new character to the beginning of the accumulator. ⋆ What is the identity for concatenation? ⋆ (What can you concatenate with without changing the answer?) ⋆ The empty string!

instr = input("Enter a string: ") reversed = "" for char in instr: reversed = char + reversed print(instr, "backwards is", reversed) reverse.py

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 22 / 31

slide-129
SLIDE 129

More accumulators

Reversing a string.

◮ Our accumulator will be a string. ◮ We’ll loop over the characters of the input string. ◮ Concatenate each new character to the beginning of the accumulator. ⋆ What is the identity for concatenation? ⋆ (What can you concatenate with without changing the answer?) ⋆ The empty string!

instr = input("Enter a string: ") reversed = "" for char in instr: reversed = char + reversed print(instr, "backwards is", reversed) reverse.py

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 22 / 31

slide-130
SLIDE 130

Previous-current loop

Sometimes a loop needs two items from the sequence at once. Drawing lines, computing distances. Or to see if user input has changed.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 23 / 31

slide-131
SLIDE 131

Previous-current loop

Sometimes a loop needs two items from the sequence at once. Drawing lines, computing distances. Or to see if user input has changed. We can save the “previous” item in a variable.

1

Initialize prev

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 23 / 31

slide-132
SLIDE 132

Previous-current loop

Sometimes a loop needs two items from the sequence at once. Drawing lines, computing distances. Or to see if user input has changed. We can save the “previous” item in a variable.

1

Initialize prev

2

Loop:

1

curr = the new item.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 23 / 31

slide-133
SLIDE 133

Previous-current loop

Sometimes a loop needs two items from the sequence at once. Drawing lines, computing distances. Or to see if user input has changed. We can save the “previous” item in a variable.

1

Initialize prev

2

Loop:

1

curr = the new item.

2

Do something with prev and curr.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 23 / 31

slide-134
SLIDE 134

Previous-current loop

Sometimes a loop needs two items from the sequence at once. Drawing lines, computing distances. Or to see if user input has changed. We can save the “previous” item in a variable.

1

Initialize prev

2

Loop:

1

curr = the new item.

2

Do something with prev and curr.

3

prev = curr

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 23 / 31

slide-135
SLIDE 135

Previous-current loop

Sometimes a loop needs two items from the sequence at once. Drawing lines, computing distances. Or to see if user input has changed. We can save the “previous” item in a variable.

1

Initialize prev

2

Loop:

1

curr = the new item.

2

Do something with prev and curr.

3

prev = curr

In the first iteration, prev is the initial value.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 23 / 31

slide-136
SLIDE 136

Previous-current loop

Sometimes a loop needs two items from the sequence at once. Drawing lines, computing distances. Or to see if user input has changed. We can save the “previous” item in a variable.

1

Initialize prev

2

Loop:

1

curr = the new item.

2

Do something with prev and curr.

3

prev = curr

In the first iteration, prev is the initial value. On following iterations, prev is the value from the preceding iteration.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 23 / 31

slide-137
SLIDE 137

Previous-current loop

Sometimes a loop needs two items from the sequence at once. Drawing lines, computing distances. Or to see if user input has changed. We can save the “previous” item in a variable.

1

Initialize prev

2

Loop:

1

curr = the new item.

2

Do something with prev and curr.

3

prev = curr

In the first iteration, prev is the initial value. On following iterations, prev is the value from the preceding iteration.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 23 / 31

slide-138
SLIDE 138

Tracing code

Code with loops, several values, etc. can get complicated. It’s good to know what it will do before running it.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 24 / 31

slide-139
SLIDE 139

Tracing code

Code with loops, several values, etc. can get complicated. It’s good to know what it will do before running it.

◮ Trial and error is good for practice and experimentation. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 24 / 31

slide-140
SLIDE 140

Tracing code

Code with loops, several values, etc. can get complicated. It’s good to know what it will do before running it.

◮ Trial and error is good for practice and experimentation. ◮ Not so good for making working, bug-free code. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 24 / 31

slide-141
SLIDE 141

Tracing code

Code with loops, several values, etc. can get complicated. It’s good to know what it will do before running it.

◮ Trial and error is good for practice and experimentation. ◮ Not so good for making working, bug-free code.

We’ll learn several debugging techniques in class.

◮ One of the simplest and most useful is tracing. ⋆ Also known as a “desk check”. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 24 / 31

slide-142
SLIDE 142

Tracing code

Code with loops, several values, etc. can get complicated. It’s good to know what it will do before running it.

◮ Trial and error is good for practice and experimentation. ◮ Not so good for making working, bug-free code.

We’ll learn several debugging techniques in class.

◮ One of the simplest and most useful is tracing. ⋆ Also known as a “desk check”. ◮ Run though code line-by-line, simulating its behavior. ◮ Keep track of the variables and output. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 24 / 31

slide-143
SLIDE 143

Tracing code

Code with loops, several values, etc. can get complicated. It’s good to know what it will do before running it.

◮ Trial and error is good for practice and experimentation. ◮ Not so good for making working, bug-free code.

We’ll learn several debugging techniques in class.

◮ One of the simplest and most useful is tracing. ⋆ Also known as a “desk check”. ◮ Run though code line-by-line, simulating its behavior. ◮ Keep track of the variables and output. ◮ Pretend you are the interpreter Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 24 / 31

slide-144
SLIDE 144

Tracing code

Code with loops, several values, etc. can get complicated. It’s good to know what it will do before running it.

◮ Trial and error is good for practice and experimentation. ◮ Not so good for making working, bug-free code.

We’ll learn several debugging techniques in class.

◮ One of the simplest and most useful is tracing. ⋆ Also known as a “desk check”. ◮ Run though code line-by-line, simulating its behavior. ◮ Keep track of the variables and output. ◮ Pretend you are the interpreter Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 24 / 31

slide-145
SLIDE 145

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-146
SLIDE 146

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) –

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-147
SLIDE 147

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) – 2 (50, 50) –

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-148
SLIDE 148

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) – 2 (50, 50) – 3 (50, 50) (400, 50)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-149
SLIDE 149

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) – 2 (50, 50) – 3 (50, 50) (400, 50) 4 (50, 50) (400, 50) One line

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-150
SLIDE 150

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) – 2 (50, 50) – 3 (50, 50) (400, 50) 4 (50, 50) (400, 50) One line 5 (400, 50) (400, 50)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-151
SLIDE 151

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) – 2 (50, 50) – 3 (50, 50) (400, 50) 4 (50, 50) (400, 50) One line 5 (400, 50) (400, 50) 2 1 (400, 50) (400, 50)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-152
SLIDE 152

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) – 2 (50, 50) – 3 (50, 50) (400, 50) 4 (50, 50) (400, 50) One line 5 (400, 50) (400, 50) 2 1 (400, 50) (400, 50) 3 1 (400, 50) (200, 300)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-153
SLIDE 153

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) – 2 (50, 50) – 3 (50, 50) (400, 50) 4 (50, 50) (400, 50) One line 5 (400, 50) (400, 50) 2 1 (400, 50) (400, 50) 3 1 (400, 50) (200, 300) 4 1 (400, 50) (200, 300) Another line

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-154
SLIDE 154

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) – 2 (50, 50) – 3 (50, 50) (400, 50) 4 (50, 50) (400, 50) One line 5 (400, 50) (400, 50) 2 1 (400, 50) (400, 50) 3 1 (400, 50) (200, 300) 4 1 (400, 50) (200, 300) Another line 5 1 (200, 300) (200, 300)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-155
SLIDE 155

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) – 2 (50, 50) – 3 (50, 50) (400, 50) 4 (50, 50) (400, 50) One line 5 (400, 50) (400, 50) 2 1 (400, 50) (400, 50) 3 1 (400, 50) (200, 300) 4 1 (400, 50) (200, 300) Another line 5 1 (200, 300) (200, 300)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-156
SLIDE 156

Tracing a previous-current loop

1: prev = get mouse 2: for i in range(2): 3: curr = get mouse 4: draw line from prev to curr 5: prev = curr Line i prev curr

  • utput

1 – (50, 50) – 2 (50, 50) – 3 (50, 50) (400, 50) 4 (50, 50) (400, 50) One line 5 (400, 50) (400, 50) 2 1 (400, 50) (400, 50) 3 1 (400, 50) (200, 300) 4 1 (400, 50) (200, 300) Another line 5 1 (200, 300) (200, 300)

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 25 / 31

slide-157
SLIDE 157

Drawing program

Let’s write a program that lets the user click on a sequence of points to draw a path.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 26 / 31

slide-158
SLIDE 158

Drawing program

Let’s write a program that lets the user click on a sequence of points to draw a path. What do we need to draw a line?

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 26 / 31

slide-159
SLIDE 159

Drawing program

Let’s write a program that lets the user click on a sequence of points to draw a path. What do we need to draw a line?

◮ Two points. ◮ The previous point, and the new one. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 26 / 31

slide-160
SLIDE 160

Drawing program

Let’s write a program that lets the user click on a sequence of points to draw a path. What do we need to draw a line?

◮ Two points. ◮ The previous point, and the new one.

We’ll have a loop where the user clicks on points.

◮ Draw a line from the previous point to the new one. ◮ No line for the first point. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 26 / 31

slide-161
SLIDE 161

Drawing program

Let’s write a program that lets the user click on a sequence of points to draw a path. What do we need to draw a line?

◮ Two points. ◮ The previous point, and the new one.

We’ll have a loop where the user clicks on points.

◮ Draw a line from the previous point to the new one. ◮ No line for the first point. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 26 / 31

slide-162
SLIDE 162

Flag variables

A flag is another word for a boolean variable.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 27 / 31

slide-163
SLIDE 163

Flag variables

A flag is another word for a boolean variable. Often used with a loop, like an accumulator.

◮ Set the flag to True or False before the loop. ◮ Inside the loop, maybe set it to the opposite. ◮ After the loop, check the flag’s value. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 27 / 31

slide-164
SLIDE 164

Common patterns: any

As an example of a flag variable, let’s check whether any of a sequence of numbers is negative.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 28 / 31

slide-165
SLIDE 165

Common patterns: any

As an example of a flag variable, let’s check whether any of a sequence of numbers is negative. We’ll start with a flag. any neg = False # None so far...

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 28 / 31

slide-166
SLIDE 166

Common patterns: any

As an example of a flag variable, let’s check whether any of a sequence of numbers is negative. We’ll start with a flag. any neg = False # None so far... for number in 0, 5, 12, -1, 2: if number < 0:

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 28 / 31

slide-167
SLIDE 167

Common patterns: any

As an example of a flag variable, let’s check whether any of a sequence of numbers is negative. We’ll start with a flag. any neg = False # None so far... for number in 0, 5, 12, -1, 2: if number < 0: any neg = True # Found one!

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 28 / 31

slide-168
SLIDE 168

Common patterns: any

As an example of a flag variable, let’s check whether any of a sequence of numbers is negative. We’ll start with a flag. any neg = False # None so far... for number in 0, 5, 12, -1, 2: if number < 0: any neg = True # Found one! if any neg: # Or if any neg == True: print("Some number was negative")

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 28 / 31

slide-169
SLIDE 169

Common patterns: any

As an example of a flag variable, let’s check whether any of a sequence of numbers is negative. We’ll start with a flag. any neg = False # None so far... for number in 0, 5, 12, -1, 2: if number < 0: any neg = True # Found one! if any neg: # Or if any neg == True: print("Some number was negative") To check “some” or “any”:

◮ Initialize the flag to False. ◮ Set it to True if you find something. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 28 / 31

slide-170
SLIDE 170

Common patterns: any

As an example of a flag variable, let’s check whether any of a sequence of numbers is negative. We’ll start with a flag. any neg = False # None so far... for number in 0, 5, 12, -1, 2: if number < 0: any neg = True # Found one! if any neg: # Or if any neg == True: print("Some number was negative") To check “some” or “any”:

◮ Initialize the flag to False. ◮ Set it to True if you find something. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 28 / 31

slide-171
SLIDE 171

Common patterns: all

Checking if something is true for all inputs is the opposite of “any”:

◮ Initialize the flag to True. ◮ Set it to False if you find an exception. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 29 / 31

slide-172
SLIDE 172

Common patterns: all

Checking if something is true for all inputs is the opposite of “any”:

◮ Initialize the flag to True. ◮ Set it to False if you find an exception.

all even = True # No exception yet for number in 8, 12, 2, 1: if number % 2 != 0: # if not even all even = False if all even: print("Every number was even.")

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 29 / 31

slide-173
SLIDE 173

Common patterns: all

Checking if something is true for all inputs is the opposite of “any”:

◮ Initialize the flag to True. ◮ Set it to False if you find an exception.

all even = True # No exception yet for number in 8, 12, 2, 1: if number % 2 != 0: # if not even all even = False if all even: print("Every number was even.") Remember, you must initialize the flag before the loop!

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 29 / 31

slide-174
SLIDE 174

Adding some features

Let’s add two features to our program:

1 We’ll ask the user for the number of points. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 30 / 31

slide-175
SLIDE 175

Adding some features

Let’s add two features to our program:

1 We’ll ask the user for the number of points. ◮ Using an Entry object. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 30 / 31

slide-176
SLIDE 176

Adding some features

Let’s add two features to our program:

1 We’ll ask the user for the number of points. ◮ Using an Entry object. 2 We’ll count and display the total length of the lines. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 30 / 31

slide-177
SLIDE 177

Adding some features

Let’s add two features to our program:

1 We’ll ask the user for the number of points. ◮ Using an Entry object. 2 We’ll count and display the total length of the lines. ◮ Using an accumulator in the loop. ◮ And a Text object to display the length. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 30 / 31

slide-178
SLIDE 178

Adding some features

Let’s add two features to our program:

1 We’ll ask the user for the number of points. ◮ Using an Entry object. 2 We’ll count and display the total length of the lines. ◮ Using an accumulator in the loop. ◮ And a Text object to display the length. ◮ Distance formula: dist =

  • (x2 − x1)2 + (y2 − y1)2

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 30 / 31

slide-179
SLIDE 179

Adding some features

Let’s add two features to our program:

1 We’ll ask the user for the number of points. ◮ Using an Entry object. 2 We’ll count and display the total length of the lines. ◮ Using an accumulator in the loop. ◮ And a Text object to display the length. ◮ Distance formula: dist =

  • (x2 − x1)2 + (y2 − y1)2

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 30 / 31

slide-180
SLIDE 180

Testing loops

How to test a loop? Verify that it runs the correct number of times.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31

slide-181
SLIDE 181

Testing loops

How to test a loop? Verify that it runs the correct number of times. What if the number of iterations is controlled by the user?

◮ For example, our drawing program. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31

slide-182
SLIDE 182

Testing loops

How to test a loop? Verify that it runs the correct number of times. What if the number of iterations is controlled by the user?

◮ For example, our drawing program. ◮ What situations might cause an error? ⋆ The code might fail when the loop doesn’t run. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31

slide-183
SLIDE 183

Testing loops

How to test a loop? Verify that it runs the correct number of times. What if the number of iterations is controlled by the user?

◮ For example, our drawing program. ◮ What situations might cause an error? ⋆ The code might fail when the loop doesn’t run. ⋆ Or it might fail on the first iteration. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31

slide-184
SLIDE 184

Testing loops

How to test a loop? Verify that it runs the correct number of times. What if the number of iterations is controlled by the user?

◮ For example, our drawing program. ◮ What situations might cause an error? ⋆ The code might fail when the loop doesn’t run. ⋆ Or it might fail on the first iteration. ⋆ Or it might only fail with multiple iterations. Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31

slide-185
SLIDE 185

Testing loops

How to test a loop? Verify that it runs the correct number of times. What if the number of iterations is controlled by the user?

◮ For example, our drawing program. ◮ What situations might cause an error? ⋆ The code might fail when the loop doesn’t run. ⋆ Or it might fail on the first iteration. ⋆ Or it might only fail with multiple iterations. ◮ So you need three test cases: 1

The loop doesn’t run at all.

2

The loop runs once.

3

The loop runs several times.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31

slide-186
SLIDE 186

Testing loops

How to test a loop? Verify that it runs the correct number of times. What if the number of iterations is controlled by the user?

◮ For example, our drawing program. ◮ What situations might cause an error? ⋆ The code might fail when the loop doesn’t run. ⋆ Or it might fail on the first iteration. ⋆ Or it might only fail with multiple iterations. ◮ So you need three test cases: 1

The loop doesn’t run at all.

2

The loop runs once.

3

The loop runs several times.

The three most important numbers in CS

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31

slide-187
SLIDE 187

Testing loops

How to test a loop? Verify that it runs the correct number of times. What if the number of iterations is controlled by the user?

◮ For example, our drawing program. ◮ What situations might cause an error? ⋆ The code might fail when the loop doesn’t run. ⋆ Or it might fail on the first iteration. ⋆ Or it might only fail with multiple iterations. ◮ So you need three test cases: 1

The loop doesn’t run at all.

2

The loop runs once.

3

The loop runs several times.

The three most important numbers in CS: 0

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31

slide-188
SLIDE 188

Testing loops

How to test a loop? Verify that it runs the correct number of times. What if the number of iterations is controlled by the user?

◮ For example, our drawing program. ◮ What situations might cause an error? ⋆ The code might fail when the loop doesn’t run. ⋆ Or it might fail on the first iteration. ⋆ Or it might only fail with multiple iterations. ◮ So you need three test cases: 1

The loop doesn’t run at all.

2

The loop runs once.

3

The loop runs several times.

The three most important numbers in CS: 0, 1

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31

slide-189
SLIDE 189

Testing loops

How to test a loop? Verify that it runs the correct number of times. What if the number of iterations is controlled by the user?

◮ For example, our drawing program. ◮ What situations might cause an error? ⋆ The code might fail when the loop doesn’t run. ⋆ Or it might fail on the first iteration. ⋆ Or it might only fail with multiple iterations. ◮ So you need three test cases: 1

The loop doesn’t run at all.

2

The loop runs once.

3

The loop runs several times.

The three most important numbers in CS: 0, 1, many.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31

slide-190
SLIDE 190

Testing loops

How to test a loop? Verify that it runs the correct number of times. What if the number of iterations is controlled by the user?

◮ For example, our drawing program. ◮ What situations might cause an error? ⋆ The code might fail when the loop doesn’t run. ⋆ Or it might fail on the first iteration. ⋆ Or it might only fail with multiple iterations. ◮ So you need three test cases: 1

The loop doesn’t run at all.

2

The loop runs once.

3

The loop runs several times.

The three most important numbers in CS: 0, 1, many.

Neil Moore (UK CS) CS 115 Lecture 10 Fall 2015 31 / 31