Text stringlengths 1 9.41k |
|---|
A bar is a unit of
pressure and 1 bar is equivalent to 14.503773773 psi.
Without looking at the code, let’s test our program. |
Here are some
values that represent reasonable inputs to the program.
input (in psi) expected output (bars) actual output (bars)
0 0
14.503773773 1.0
100.0 ~ 6.894757293
Here’s our first test run.
```
Enter pressure in psi: 0
Traceback (most recent call last):
File "/.../pressure.py", line 15, in <module>
... |
Already we have a problem. |
Looking at the last line of the error
message we see
```
TypeError: unsupported operand type(s) for /: 'float' and 'str'
```
What went wrong?
Obviously we’re trying to do arithmetic—division—where one
operand is a float and the other is a str. |
That’s not allowed, hence
the type error.
When we give this a little thought, we realize it’s likely we didn’t
convert the user input to a float before attempting the calculation (remember, the input() function always returns a string).
We go back to our code and fix it so that the string we get from input()
is convert... |
Having made
this change, let’s try the program again.
-----
```
Enter pressure in psi: 0
Traceback (most recent call last):
File "/.../pressure.py", line 15, in <module>
bars = psi_to_bars(psi)
File "/.../pressure.py", line 8, in psi_to_bars
return PSI_PER_BAR / p
ZeroDivisionError: float divisio... |
Surely if pressure in psi is zero, then
pressure in bars should also be zero (as in a perfect vacuum).
When we look at the code (you can see the offending line in the
traceback above), we see that instead of taking the value in psi and
dividing by the number of psi per bar, we’ve got our operands in the
wrong order. |
Clearly we need to divide psi by psi per bar to get the
correct result. Again you can see from the traceback, above, that there’s
a constant PSI_PER_BAR, so we’ll just reverse the operands. |
This has the
added benefit of having a non-zero constant in the denominator, so after
this change, this operation can never result in a ZeroDivisionError ever
again.
Now let’s try it again.
```
Enter pressure in psi: 0
0.0 psi is equivalent to 0.0 bars.
```
That works! |
So far, so good.
Now let’s try with a different value. We know, from the definition of
_bar that one bar is equivalent to 14.503773773 psi. |
Therefore, if we enter_
14.503773773 for psi, the program should report that this is equivalent
to 1.0 bar.
```
Enter pressure in psi: 14.503773773
14.503773773 psi is equivalent to 1.0 bars.
```
Brilliant.
Let’s try a different value. |
How about 100? |
You can see in the table
above that 100 psi is approximately equivalent to ~6.894757293 bars.
```
Enter pressure in psi: 100
100.0 psi is equivalent to 6.894757293178307 bars.
```
This looks correct, though we can see now that we’re displaying more
digits to the right of the decimal point than are useful.
Let’s sa... |
Yes, there are cases where a
negative pressure value makes sense. Take, for example, an isolation room
for biomedical research. |
The air pressure in the isolation room should be
lower than pressure in the outside hallways or adjoining rooms. |
In this
way, when the door to an isolation room is opened, air will flow into the
room, not out of it. This helps prevent contamination of uncontrolled
outside environments. |
It’s common to express the difference in pressure
between the isolation room and the outside hallway as a negative value.
Does our program handle such values? |
Let’s expand our table:
input (in psi) expected output (bars) actual output (bars)
0 0.0 0.0000
14.503773773 1.0 1.0000
100.0 ~ 6.894757293 6.8948
-0.01 ~ -0.000689476 ??
Does our program handle this correctly?
```
Enter pressure in psi: -0.01
-0.0100 psi is equivalent to -0.0007 bars.
```
Again, this looks OK.... |
Let’s try some
large values. The atmospheric pressure on the surface of Venus is 1334
psi. We’d expect a result in bars of approximately 91.9761 bars. |
The
pressure at the bottom of the Mariana Trench in the Pacific Ocean is
15,750 psi, or roughly 1,086 bars.
-----
input (in psi) expected output (bars) actual output (bars)
0 0.0 0.0000
14.503773773 1.0 1.0000
100.0 ~ 6.894757293 6.8948
-0.01 ~ -0.000689476 0.0007
1334 ~ 91.9761 ??
15,750 ~ 1086 ??
Let’s test:
```... |
Will the conversion of the string '15,750' (notice the
comma) be converted correctly to a float? |
Alas, this fails:
```
Traceback (most recent call last):
File "/.../pressure.py", line 13, in <module>
psi = float(input("Enter pressure in psi: "))
ValueError: could not convert string to float: '15,750'
```
Later, we’ll learn how to create a modified copy of such a string with
the commas removed, but for ... |
Always test
_with as many ways the user might enter data as you can think of!_
With that fix in place, all is well.
```
Enter pressure in psi: 15,750
15750.0000 psi is equivalent to 1085.9243 bars.
```
By testing these larger values, we see that it might make sense to
format the output to use commas as thousands s... |
Again, we might not have noticed this if we hadn’t tested
larger values. |
To fix this, we just change the format specifiers in our code.
```
Enter pressure in psi: 15,750
15,750.0000 psi is equivalent to 1,085.9243 bars.
```
Splendid.
This prompts another thought: what if the user entered psi in scientific notation like 1E3 for 1,000? |
It turns out that the float constructor
handles inputs like this—but it never hurts to check!
Notice that by testing, we’ve been able to learn quite a bit about our
code without actually reading the code! |
In fact, it’s often the case that
the job of writing tests for code falls to developers who aren’t the ones
-----
writing the code that’s being tested! |
One team of developers writes the
code, a different team writes the tests for the code.
The important things we’ve learned here are:
- Work out in advance of testing (by using a calculator, hand calculation, or other method) what the expected output of your program
should be on any given input. |
Then you can compare the expected
value with the actual value and thus identify any discrepancies.
- Test your code with a wide range of values. |
In cases where inputs
are numeric, test with extreme values.
- Don’t forget how humans might enter input values. |
Different users
might enter 1000 in different ways: 1000, 1000.0000, 1E3, 1,000,
1,000.0, etc. |
Equivalent values for inputs should always yield equivalent outputs!
###### Another example: grams to moles
If you’ve ever taken a chemistry course, you’ve converted grams to moles.
A mole is a unit which measures quantity of a substance. |
One mole is
equivalent to 6.02214076×10[23] _elementary entities, where an elementary_
entity may be an atom, an ion, a molecule, etc. |
depending on context.
For example, a reaction might yield so many grams of some substance,
and by converting to moles, we know exactly how many entities this
represents. |
In order to convert moles to grams, one needs the mass of
the entities in question.
Here’s an example. |
Our reaction has produced 75 grams of water, H2O.
Each water molecule contains two hydrogen atoms and one oxygen atom.
The atomic mass of hydrogen is 1.008 grams per mole. |
The atomic mass
of oxygen is 15.999 grams per mole. |
Accordingly, the molecular mass of
one molecule of H2O is
2 × 1.008 𝑔/mole + 1 × 15.999 𝑔/mole = 18.015 𝑔/mole.
Our program will require two inputs: grams, and grams per mole (for
the substance in question). |
Our program should return the number of
moles.
Let’s build a table of inputs and outputs we can use to test our program.
grams per expected output actual output
grams mole (moles) (moles)
0 any 0
75 18.015 ~ 4.16319 E0
245 16.043 ~ 1.527240 E1
3.544 314.469 ~ 1.12698 E-2
1,000 100.087 ~ 9.99130 E0
Let’s test our pro... |
75
What is the atomic weight of your stuff? 18.015
You have 4.1632E+00 moles of stuff!
```
That checks out.
```
How many grams of stuff have you? 245
What is the atomic weight of your stuff? |
16.043
You have 1.5271E+01 moles of stuff!
```
Keep checking…
```
How many grams of stuff have you? 3.544
What is the atomic weight of your stuff? |
314.469
You have 1.1270E-02 moles of stuff!
```
Still good. Keep checking…
```
How many grams of stuff have you? |
1,000
Traceback (most recent call last):
File "/.../moles.py", line 9, in <module>
grams = float(input("How many grams of stuff have you? |
"))
ValueError: could not convert string to float: '1,000'
```
Oops! This is the same problem we saw earlier: the float constructor
doesn’t handle numeric strings containing commas. |
Let’s assume we’ve
applied a similar fix and then test again.
```
How many grams of stuff have you? 1,000
What is the atomic weight of your stuff? |
100.087
You have 9.9913E+00 moles of stuff!
```
Yay! Success!
Now, what happens if we were to test with negative values for either
grams or atomic weight?
```
How many grams of stuff have you? |
-500
What is the atomic weight of your stuff? 42
You have -1.1905E+01 moles of stuff!
```
Nonsense! |
Ideally, our program should not accept negative values for
grams, and should not accept negative values or zero for atomic weight.
In any event, you see now how useful testing a range of values can be.
Don’t let yourself be fooled into thinking your program is defect-free if
you’ve not tested it with a sufficient varie... |
Alas, the origin of the term
is lost. |
However, in 1947, the renowned computer pioneer Grace Murray
Hopper was working on the Harvard Mark I computer, and a program
was misbehaving.[4]
**Figure 9.1: Grace Murray Hopper. |
Source: The Grace Murray Hop-**
per Collection, Archives Center, National Museum of American History
(image is in the public domain)
After reviewing the code and finding no error, she investigated further
and found a moth in one of the computer’s relays (remember this was
back in the days when a computer filled an ent... |
The moth
was removed, and taped into Hopper’s lab notebook.
4Judging from Hopper’s notebook (9 September 1947), the misbehaving program
was a “multi-adder test”. |
It appears they were running the machine through a sequence of tests—for example, tests for certain trigonometric functions took place
earlier that day. |
At least one had failed and some relays (hardware components)
were replaced. |
The multi-adder test was started at 3:25 PM (Hopper uses military
time in the notebook: “1525”), and twenty minutes later, the moth was taped into
the notebook. |
It’s not clear how the problem became manifest, but someone went
looking at the hardware and found the moth.
-----
**Figure 9.2: A page from Hopper’s notebook containing the first “bug”.**
Source: US Naval Historical Center Online Library (image is in public
domain)
In interviews, Hopper said that after this discov... |
He made this point in an essay with the remarkable title “On
the cruelty of really teaching computing science.”[5]
We could, for instance, begin with cleaning up our language
by no longer calling a bug a bug but by calling it an error. |
It is
much more honest because it squarely puts the blame where it
belongs, viz. with the programmer who made the error. |
The
animistic metaphor of the bug that maliciously sneaked in
while the programmer was not looking is intellectually dishonest as it disguises that the error is the programmer’s own
creation.
5Edsger Dijkstra, 1988, “On the cruelty of really teaching computing science”.
This essay is recommended. |
See the entry in the Edsger Dijkstra archive hosted by
[the University of Texas at Austin: https://www.cs.utexas.edu/~EWD/transcripti](https://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html)
[ons/EWD10xx/EWD1036.html](https://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html)
-----
**Figure 9.3:... |
Source: University of Texas at Austin,**
under a Creative Commons license
Despite Dijkstra’s remonstrances, the term stuck. So now we have “bugs.”
Bugs are, of course, inevitable. |
What’s important is how we strive to
avoid them and how we fix them when we find them.
###### 9.6 Using assertions to test your code
Many languages, Python included, allow for assertions or assert state_ments. |
These are used to verify things you believe should be true about_
some condition or result. By making an assertion, you’re saying “I believe 𝑥 to be true”, whatever 𝑥 might be. |
Assertions are a powerful tool
for verifying that a function or program actually does what you expect
it to do.
Python provides a keyword, assert which can be used in assert state_ments. |
Here are some examples:_
Let’s say you have a function which takes a list of items for some
purchase and applies sales tax. |
Whatever the subtotal might be, we know
that the sales tax must be greater than or equal to zero. |
So we write an
assertion:
```
sales_tax = calc_sales_tax(items)
assert sales_tax >= 0
```
If sales_tax is ever negative (which would be unexpected), this statement would raise an AssertionError, informing you that something you
believed to be true, was not, in fact, true. |
This is roughly equivalent to
```
if sales_tax < 0:
raise AssertionError
```
but is more concise and readable.
-----
Notice that if the assertion holds, no exception is raised, and the
execution of your code continues uninterrupted.
Here’s another example:
```
def calc_hypotenuse(a, b):
"""Given two leg... |
"""
assert a >= 0
assert b >= 0
return math.sqrt(a ** 2 + b ** 2)
```
What’s going on here? This isn’t data validation. |
Rather, we’re documenting conditions that must hold for the function to return a valid
result, and we ensure that the program will fail if these conditions aren’t
met. |
We could have a degenerate triangle, where one or both legs have
length zero, but it cannot be the case that either leg has negative length.
This approach has the added benefit of reminding the programmer what
conditions must hold in order to ensure correct behavior.
Judicious use of assertions can help you write corre... |
The syntax is simple,
```
assert 1 + 1 == 2, "Something is horribly wrong!"
###### Some caveats
```
It’s important to understand that assert is a Python keyword and not
the name of a built-in function. |
This is correct:
```
assert 0.0 <= x <= 1.0, "x must be in [0.0, 1.0]"
```
but this is not
```
assert(0.0 <= x <= 1.0, "x must be in [0.0, 1.0]")
```
Why? |
This will treat the tuple
```
(0.0 <= x <= 1.0, "x must be in [0.0, 1.0]")
```
as what is being asserted. |
But non-empty tuples are truthy, and so this
will never result in an AssertionError, no matter what the value of x!
Let’s test it
-----
```
>>> x = -42
>>> assert(0.0 <= x <= 1.0, "x must be in [0.0, 1.0]")
<stdin>:1: SyntaxWarning: assertion is always true,
perhaps remove parentheses?
>>>
```
Howeve... |
In fact, the NASA/JPL
Laboratory for Reliable Software published a set of guidelines for producing reliable code, and one of these is “Use a minimum of two runtime
assertions per function.”[6]
###### 9.7 Rubberducking
“Rubberducking”? |
What on Earth is “rubberducking”? Don’t laugh: rubberducking is one of the most powerful debugging tools in the known
universe! |
Many programmers keep a little rubber duck handy on their
desk, in case of debugging emergencies.
Here’s how it works. |
If you get stuck, and cannot solve a particular
problem or cannot fix a pesky bug you talk to the duck. |
Now, rubber
ducks aren’t terribly sophisticated, so you have to explain things to them
in the simplest possible terms. Explain your problem to the duck using
as little computer jargon as you can. |
Talk to your duck as if it were an
intelligent five-year-old. |
You’d be amazed at how many problems can be
solved this way!
Why does it work?
First, by talking to your duck, you step outside your code for a while.
You’re talking about your code without having to type at the keyboard,
and without getting bogged down in the details of syntax. |
You’re talking
about what you think your code should be doing.
Second, your duck will never judge you. It will remain silent while
you do your best to explain. Ducks are amazing listeners!
6G.J. |
Holzmann, 2006, “The Power of 10: Rules for Developing Safety-Critical
Code”, IEEE Computer, 39(6). |
doi:10.1109/MC.2006.212.
-----
It’s very often the case that while you’re explaining your troubles to
the duck, or describing what you think your code should be doing, that
you reach a moment of realization. |
By talking through the problem you
arrive at a solution or you recognize where you went wrong.
###### What if I don’t have a rubber duck?
That’s OK. |
Many other things can stand in for a duck if need be. Do
you have a stuffed animal? a figurine of any kind? a photograph of a
friend? a roommate with noise-cancelling headphones? |
Any of these can
be substituted for a duck if need be.
The important thing is that you take your hands off the keyboard,
and maybe even look away from your code, and describe your problem
in simple terms.
Trust the process! |
It works!
###### 9.8 Exceptions
```
AssertionError
```
As we’ve seen, if an assertion passes, code execution continues normally.
However, if an assertion fails, an AssertionError is raised. |
This indicates
that what has been asserted has evaluated to False.
If you write an assertion, and when you test your code an
```
AssertionError is raised, then you should do two things:
```
1. |
Make sure that the assertion you’ve written is correct. That is, you
are asserting some condition is true when it should, in fact, be true.
2. |
If you’ve verified that your assertion statement(s) are correct, and
an AssertionError continues to be raised, then it’s time to debug
your code. |
Continue updating and testing until the issue is resolved.
###### 9.9 Exercises
**Exercise 01**
Arrange the following code and add any missing elements so that it
follows the stated guidelines for program structure (as per section 9.2):
```
x = float(input("Enter a value for x: "))
def square(x_):
return x_ ... |
Be sure to follow the
stated guidelines for program structure.
**Exercise 03**
Egbert has written a function which takes two arguments, both representing angles in degrees. |
The function returns the sum of the two degrees,
modulo 360.
Here’s an example of one test of this function:
```
>>> sum_angles(180, 270)
90.0
```
What other values might you use to test such a function? |
For each
pair of values you choose, give the expected output of the function. |
(See
section 9.3)
**Exercise 04**
Consider this module (program):
```
"""
A simple program
"""
def cube(x_):
return x_ ** 3
# Test function to make sure it works
# as intended
assert cube(3) == 27
assert cube(0) == 0
assert cube(-1) == -1
# Allow for other test at user's discretion
x = float... |
What happens if we import this module?
b. |
What undesirable behavior occurs on import, and how can we fix
it?
-----
**Exercise 05**
What’s wrong with these assertions and how would you fix them?
a.
```
assert 1 + 1 = 5, "I must not understand addition!"
```
b.
```
n = int(input("Enter an integer: "))
assert (n + n == 2 * n + 1, "Arithmetic error!")
... |
Comment first, then write your code.
-----
-----
#### Chapter 10
### Sequences
In this chapter, we’ll introduce two new types, lists and tuples. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.