lecture 6 - ceprofs · 2019-09-11 · lecture 6 writing and testing programs what are we going to...

9
9/11/19 1 Lecture 6 Writing and Testing Programs What are we going to cover today? Writing larger programs Commenting Design Testing Writing larger programs As programs become larger and more complex, it becomes more and more important to plan out how they will work. One subfield of computer science, called software engineering, deals with the processes for constructing large pieces of software. We’re not going to be handling large software in this course, but some of the principles for good software construction practice still apply. Today, we’ll look at a couple of them. Comments Comments are descriptive text placed into the code of the program. Comments (for the most part) are NOT executed. They are purely for human benefit, not for the computer! As the computer reads through the code, comments are just skipped over. Comments are meant to help people understand what the purpose of the code is. Others who will read your code You, when you come back to your code in the future You, when you are dealing with a large program that’s hard to keep track of Comments in Python To create a comment in Python, you can place a # in front of the comment you want. The # and everything after it on that line are totally ignored # Here is a comment before a line of code a = 3 # Here is a comment at the end of a line of code # b = 4 This whole line is a comment: the b = 4 part is not executed Using Comments You should use comments to: Describe the purpose of a line or a section of code Define the purpose of a particular variable Clarify a computation that is not present Give a reference to some external source that a person reading the code might need to be aware of Clearly separate “sections” of code from each other Do not use comments to: Restate what should be obvious from reading the code Add things that are irrelevant to the code itself Except for header information required for our class!

Upload: others

Post on 11-Jun-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 6 - CEProfs · 2019-09-11 · Lecture 6 Writing and Testing Programs What are we going to cover today? •Writing larger programs •Commenting •Design •Testing Writing

9/11/19

1

Lecture 6Writing and Testing Programs

What are we going to cover today?

• Writing larger programs

• Commenting

• Design

• Testing

Writing larger programs

• As programs become larger and more complex, it becomes more and more important to plan out how they will work.• One subfield of computer science, called software engineering, deals

with the processes for constructing large pieces of software.• We’re not going to be handling large software in this course, but

some of the principles for good software construction practice still apply.• Today, we’ll look at a couple of them.

Comments

• Comments are descriptive text placed into the code of the program.• Comments (for the most part) are NOT executed.• They are purely for human benefit, not for the computer!• As the computer reads through the code, comments are just skipped over.

• Comments are meant to help people understand what the purpose of the code is.• Others who will read your code• You, when you come back to your code in the future• You, when you are dealing with a large program that’s hard to keep track of

Comments in Python

• To create a comment in Python, you can place a # in front of the comment you want.• The # and everything after it on that line are totally ignored

# Here is a comment before a line of codea = 3 # Here is a comment at the end of a line of code# b = 4 This whole line is a comment: the b = 4 part is not executed

Using Comments

• You should use comments to:• Describe the purpose of a line or a section of code• Define the purpose of a particular variable• Clarify a computation that is not present• Give a reference to some external source that a person reading the code

might need to be aware of• Clearly separate “sections” of code from each other

• Do not use comments to:• Restate what should be obvious from reading the code• Add things that are irrelevant to the code itself

• Except for header information required for our class!

Page 2: Lecture 6 - CEProfs · 2019-09-11 · Lecture 6 Writing and Testing Programs What are we going to cover today? •Writing larger programs •Commenting •Design •Testing Writing

9/11/19

2

The comment that’s not a comment

• Sometimes, you will see people use a triple-quoted string as a type of comment.• Either with single quotes or double quotes: ''' or """

• Basically, you can put anything in a triple-quoted string, but not assign the string to anything, and the string is effectively ignored, thus it’s like a comment.

a = 3''' This is a string that spansmultiple lines, and that acts sort-of likea comment '''

• People sometimes use this when they want a comment spanning multiple lines.• But, it is better practice not to use this!

• Later, we’ll see a real use for this sort of “comment”

Visual Breaks in Code

• Whitespace refers to blank lines and spaces in code• Whitespace can be used to separate different sections of the code. • Helps identify sections of the code that have different purposes

a = 3b = 5

print(“The sum is”, a+b)• Sometimes, comments are used to provide visual breaks:• ##################################• ##### New Section #####

Program Design

• When faced with a large task, the first thing to do is to think.• This goes for almost anything: building a house, designing a bridge, etc.• Writing software is the same way: think before writing code!

• Usually, the time spent thinking about a problem before trying to solve it will save more time later.• There are many approaches to program design, but all of them

involve stopping to think about design before trying to implement.

A first approach to program design

• Consider the major stages the program will follow• Typically, a sequence of operations• e.g. Get input from user -> Perform calculation -> Output result

• List these in order (outside of a program)• Convert your steps of the program to comments• Fill in the regions between comments with code

Example (initial steps/design):

• Task: write a program to calculate a person’s BMI and output their weight category.

• Steps:1. Read user’s height and weight2. Calculate BMI3. Output weight category

Example: Making steps into comments

#Read user's height and weight

#Calculate BMI

#Output weight category

Page 3: Lecture 6 - CEProfs · 2019-09-11 · Lecture 6 Writing and Testing Programs What are we going to cover today? •Writing larger programs •Commenting •Design •Testing Writing

9/11/19

3

Example: Filling in code#Read user's height and weight

height = float(input("Enter height in inches: "))

weight = float(input("Enter weight in pounds: "))

#Calculate BMI

BMI = weight/(height*height)*709

#Output weight category

if BMI < 18.5:

print("Underweight")

elif BMI <=25:

print("Normal Weight")

elif BMI <=30:

print("Overweight")

else:

print("Obese")

Writing Tests

• To find if a program is working, you need to test it!• Never assume it’s working without testing• You will need to understand what your code should do

• This is sometimes more difficult than it might seem – you often are writing a program since it is difficult to do the same thing by hand

• Tests should be basic input to a program (or part of a program) where you know what you should expect as output• Tests could be values you enter as a user• Tests could be values of variables set in the code

Writing Tests (ideally)

• Ideally, write your tests before you write your program • This will help you think through what the program should be doing• This will give you a way to test your code as soon as you write it• Sometimes it helps to have someone write tests who is not writing the code

• Ideally, if you do a good job writing tests, then if your code passes all tests, it should work.

• Realistically, people often write tests after writing (at least some) code and don’t write sufficiently thorough tests

How to write tests

• Test the “Typical” case• You usually don’t need to test too many of these – just enough to ensure the

program is basically working

• Test the “edge” cases or “corner” cases• These are the “special” cases, that are less common/typical

• Example: on a chess board:• The “typical” case would be a square near the middle (touching 8 other squares)• Would also want to test edge squares (touching 5 other squares), and corner squares

(touching 3 other squares)• This is where the term “edge” case or “corner” case comes from!

Exercise: Coming up with tests

• Imagine a program that had to process dates in a year• What dates would you test?

Exercise: Coming up with tests

• Imagine a program that had to process dates in a year• What dates would you test?

• Typical: some dates in middle of year: e.g. May 25 or November 9• Some “edge” cases:• First/last days of months: July 1, June 30, July 31, February 28• First/last day of the year: January 1, December 31

• Special case: February 29

Page 4: Lecture 6 - CEProfs · 2019-09-11 · Lecture 6 Writing and Testing Programs What are we going to cover today? •Writing larger programs •Commenting •Design •Testing Writing

9/11/19

4

Implementing Tests

• If you have a “complete” program, you can test the whole process.• But, it often helps to test just a piece of the program. To do this:• Can read in values from a user• Can set variable values to specific test cases• Can print out values at various points using print statements

• When you find something doesn’t work, you need to fix it!• This is called debugging: find where the program is failing, determine the

error, and fix it.• Later, we will learn more formal debugging approaches

An analogy for software construction

• There are two common architectural forms, both of which have produced structures that have lasted since ancient times:

Pyramids Arches

An analogy for software construction

• Though both pyramids and arches end up with “good” structures, the way they are built is quite different.

• Pyramid: • Place stones at the bottom. Once stones underneath are set, place more on

top of them.• Arch:• Place all stones in the arch, holding it up with temporary scaffolding. Place all

stones in the arch before removing the scaffolding.

An analogy for software construction

• With Pyramids, you can stop at any point• You always have a stable structure.• You can test the lower levels before adding upper levels

• With Arches, you can’t stop at an intermediate point• The structure is not stable until every stone is in place• You can’t really test the arch until all pieces are there

• So, how does this relate to software construction?

Incremental Development

• Sometimes, people try to follow the “arch” style of development with their code• Only after they’ve written all of the code do they stop to test/evaluate it• If any one piece is missing or broken, the whole program falls apart!

• The “pyramid” style lets you develop incrementally• You can write small pieces of code, test them, and ensure that they are

working before adding more code• You always have a “stable” piece of software, even when not complete!

• When building software, try to use a “pyramid” process, not an “arch” process!

Example

• Let’s see development of a piece of code.• Back to our learning example, let’s say we want to compute the

concepts learned – getting a time of study from a user and computing how much they can expect to learn

Time since start of study session

Rate ofLearning 1. We might assume a constant learning rate

3. And, maybe when we get fatigued we learn worse

2. But perhaps there is a warm-upperiod where we remember whatwe had learned before

Page 5: Lecture 6 - CEProfs · 2019-09-11 · Lecture 6 Writing and Testing Programs What are we going to cover today? •Writing larger programs •Commenting •Design •Testing Writing

9/11/19

5

Thinking about the problem

• What information will we need to perform the computation?• Initial rate of learning• Time at which warmup stops• Constant rate of learning• Time when fatigue begins• Time we stop learning anything new

Time since start of study session

Rate ofLearning

• Length of study session

Thinking about the problem

• What information will we need to perform the computation?• Initial rate of learning• Time at which warmup stops• Constant rate of learning• Time when fatigue begins• Time we stop learning anything new

• What variables will we use? (might find we need more later)• rate_initial, rate_constant• time_constant, time_fatigue, time_stop• study_time

• Length of study session

What will our general process be?

• Set up specific model for learning• Setting variable values – will hard-code them

• Read time from user• Calculate the amount learned• Output result to user

Writing Code

#Set up specific model for learning

#Read time from user

#Calculate the amount learned

#Output result to user

Writing Code#Set up specific model for learningrate_initial = 0.1rate_constant = 0.2time_constant = 15time_fatigue = 60time_stop = 90

#Read time from user

#Calculate the amount learned

#Output result to user

Testing

• Typically, we should stop and test after each section• But, for this simple program, the setup has very little we can test – it’s

just variable assignment.• We WILL stop and test future sections.

Page 6: Lecture 6 - CEProfs · 2019-09-11 · Lecture 6 Writing and Testing Programs What are we going to cover today? •Writing larger programs •Commenting •Design •Testing Writing

9/11/19

6

#Set up specific model for learningrate_initial = 0.1rate_constant = 0.2

time_constant = 15time_fatigue = 60time_stop = 90

#Read time from userstudy_time = input("How long will you study? ")

#Calculate the amount learned

#Output result to user

Testing

• We’ll want to see if we’re reading the data correctly. Let’s add a single print statement in to output what we read in.

#Set up specific model for learning

rate_initial = 0.1

rate_constant = 0.2

time_constant = 15

time_fatigue = 60

time_stop = 90

#Read time from user

study_time = input("How long will you study? ")

print("Entered: ", study_time)

#Calculate the amount learned

#Output result to user

Testing

• Run the program, see if the input matches output.

How long will you study? 10Entered: 10

• OK, it seems like it’s working… But was that enough of a test?• Maybe we want to make sure we can do something with the value, so we

might also want to test that we can compute with it• Let’s try, say, adding 1 to the value we read in.

#Set up specific model for learning

rate_initial = 0.1

rate_constant = 0.2

time_constant = 15

time_fatigue = 60

time_stop = 90

#Read time from user

study_time = input("How long will you study? ")

print("Entered: ", study_time)

print("Adding 1: ", study_time+1)

#Calculate the amount learned

#Output result to user

Now test:

How long will you study? 10Entered: 10Traceback (most recent call last):File "C:/Users/John/PycharmProjects/ENGR102/Test

Development.py", line 12, in <module>print("Adding 1: ", study_time+1)

TypeError: must be str, not int

Process finished with exit code 1

Oh no!• What happened – that was an error!• If you read the output from the failure, it gives us a hint as to what went wrong

• That won’t always be the case, but it is, here

How long will you study? 10Entered: 10Traceback (most recent call last):File "C:/Users/John/PycharmProjects/ENGR102/Test Development.py", line

12, in <module>print("Adding 1: ", study_time+1)

TypeError: must be str, not int

Process finished with exit code 1

• Line number is shown, along with the statement on that line. And, it says we have a “TypeError”• We tried to add a number to a string!

Page 7: Lecture 6 - CEProfs · 2019-09-11 · Lecture 6 Writing and Testing Programs What are we going to cover today? •Writing larger programs •Commenting •Design •Testing Writing

9/11/19

7

#Set up specific model for learning

rate_initial = 0.1

rate_constant = 0.2

time_constant = 15

time_fatigue = 60

time_stop = 90

#Read time from user

study_time = input("How long will you study? ")

print("Entered: ", study_time)

print("Adding 1: ", study_time+1)

#Calculate the amount learned

#Output result to user

This is where the program failed, but it’s not where the error is.

We forgot to convert the input from a string to a number!

Fix the bug:#Set up specific model for learning

rate_initial = 0.1

rate_constant = 0.2

time_constant = 15

time_fatigue = 60

time_stop = 90

#Read time from user

study_time = float(input("How long will you study? "))

print("Entered: ", study_time)

print("Adding 1: ", study_time+1)

#Calculate the amount learned

#Output result to user

Now re-test

How long will you study? 10Entered: 10.0Adding 1: 11.0

Process finished with exit code 0

• Looks good, now…• We could do more tests, but for illustration, let’s move on.

Writing tests

• Before we write the next section, computing study, let’s think of some tests.• Study times to test: • Typical points: during the warmup, during the constant period, during the

fatigue period• Edge cases: 0, at transition points, negative values, values past stop point

Time since start of study session

Rate ofLearning

Other tests

• Need to come up with specific values for learning model, and should test with multiple such values• Will need to determine actual values.• For the values we’ve put into code, we could test study times, and expect values

of:• 0: 0• 8: 1.013• 15: 2.25• 30: 5.25• 60: 11.25• 70: 11.58• 90: 14.25• 100: 14.25 (after stop period)• -1: 0 (before)

Now write code

• Code will require if-elif-else statements• Went through an example in last lecture

• Will add comments throughout• Need a new variable to store answer: concepts_learned

• And maybe some others along the way!

• Test pieces incrementally• First write and test the warmup calculation• Then write and test the constant period of time• Then write and test fatigue period• Test all the other cases

• Will use the overall output as our test output, in this instance.

Page 8: Lecture 6 - CEProfs · 2019-09-11 · Lecture 6 Writing and Testing Programs What are we going to cover today? •Writing larger programs •Commenting •Design •Testing Writing

9/11/19

8

rate_initial = 0.1

rate_constant = 0.2

time_constant = 15

time_fatigue = 60

time_stop = 90

#Read time from user

study_time = float(input("How long will you study? "))

#Calculate the amount learned

if (study_time >=0) and (study_time <= time_constant):

#warmup period

end_learn_rate = rate_initial + (rate_constant - rate_initial) / time_constant * study_time

concepts_learned = study_time * (rate_initial + end_learn_rate) / 2

#Output result to user

print("You learned",concepts_learned,"concepts in that time.")

Now test warmup period

• Test for time 0, time 8, time 15

• For this example, we won’t have more bugs in the code, but in general, you might find them…

Adding constant period(then should test)

#Set up specific model for learning

rate_initial = 0.1

rate_constant = 0.2

time_constant = 15

time_fatigue = 60

time_stop = 90

#Read time from user

study_time = float(input("How long will you study? "))

#Calculate the amount learned

if (study_time >=0) and (study_time <= time_constant):

#warmup period

end_learn_rate = rate_initial + (rate_constant - rate_initial) / time_constant * study_time

concepts_learned = study_time * (rate_initial + end_learn_rate) / 2

elif (study_time > time_constant) and (study_time <= time_fatigue):

#constant period

concepts_learned = 2.25 #concepts learned during warmup

concepts_learned += rate_constant * (study_time - time_constant)

#Output result to user

print("You learned",concepts_learned,"concepts in that time.")

Adding fatigue period(then should test)

#Set up specific model for learning

rate_initial = 0.1

rate_constant = 0.2

time_constant = 15

time_fatigue = 60

time_stop = 90

#Read time from user

study_time = float(input("How long will you study? "))

#Calculate the amount learned

if (study_time >=0) and (study_time <= time_constant):

#warmup period

end_learn_rate = rate_initial + (rate_constant - rate_initial) / time_constant * study_time

concepts_learned = study_time * (rate_initial + end_learn_rate) / 2

elif (study_time > time_constant) and (study_time <= time_fatigue):

#constant period

concepts_learned = 2.25 #concepts learned during warmup

concepts_learned += rate_constant * (study_time - time_constant)

elif (study_time > time_fatigue) and (study_time <= time_stop):

#fatique period

concepts_learned = 11.25 #concepts learned through constant period

end_learn_rate = (study_time - time_fatigue) / (time_stop-time_fatigue)

concepts_learned += (study_time - time_fatigue) * (rate_constant * end_learn_rate) / 2

#Output result to user

print("You learned",concepts_learned,"concepts in that time.")

Adding before/after periods (then should test)

#Set up specific model for learning

rate_initial = 0.1

rate_constant = 0.2

time_constant = 15

time_fatigue = 60

time_stop = 90

#Read time from user

study_time = float(input("How long will you study? "))

#Calculate the amount learned

if (study_time >=0) and (study_time <= time_constant):

#warmup period

end_learn_rate = rate_initial + (rate_constant - rate_initial) / time_constant * study_time

concepts_learned = study_time * (rate_initial + end_learn_rate) / 2

elif (study_time > time_constant) and (study_time <= time_fatigue):

#constant period

concepts_learned = 2.25 #concepts learned during warmup

concepts_learned += rate_constant * (study_time - time_constant)

elif (study_time > time_fatigue) and (study_time <= time_stop):

#fatique period

concepts_learned = 11.25 #concepts learned through constant period

end_learn_rate = (study_time - time_fatigue) / (time_stop-time_fatigue)

concepts_learned += (study_time - time_fatigue) * (rate_constant * end_learn_rate) / 2

elif (study_time > time_stop):

#post-fatque: nothing more to learn

concepts_learned = 14.25

else:

#negative time - nothing can be learned!

concepts_leanred = 0

#Output result to user

print("You learned",concepts_learned,"concepts in that time.")

Summary

• Think about the program• What do you need to do• Determine key variables• Write some comments

• Think about testing (the earlier the better)• Code incrementally• Test each section of code after you write it

Page 9: Lecture 6 - CEProfs · 2019-09-11 · Lecture 6 Writing and Testing Programs What are we going to cover today? •Writing larger programs •Commenting •Design •Testing Writing

9/11/19

9

For more complex programs

• As the computation becomes more complex, design will increase in importance.

• There are more formalized methods for ways of designing• We’ll see a couple of these, top-down and bottom-up, later in the course