Text stringlengths 1 9.41k |
|---|
To return to our kilogram to
pound conversion program, it does not make sense for the user to enter a
negative value for the weight in kilograms. |
We might guard against this
with bounds checking.
```
POUNDS_PER_KILOGRAM = 2.204623
kg = float(input('Enter weight in kilograms: '))
if kg >= 0:
# convert kilograms to pounds and print result
else:
print('Invalid input! |
'
'Weight in kilograms must not be negative!')
```
So our program would perform the desired calculations if and only if
the weight in kilograms entered by the user were non-negative (that is,
greater than or equal to zero).
Here’s another example. |
Let’s say we’re writing a program that plays
the game evens and odds. |
This is a two-player game where one player
calls “even” or “odd”, and then the two players simultaneously reveal
zero, one, two, three, four or five fingers. |
Then the sum is calculated and
the caller wins if the sum agrees with their call.
In such a game, we’d want the user to enter an integer in the interval
[0, 5]. |
Here’s how we might validate this input:
```
fingers = int(input('Enter a number of fingers [0, 5]: '))
if fingers >= 0 and fingers <= 5:
# Generate a random integer in the range [0, 5],
# calculate sum, and report the winner.
else:
print('Invalid input!')
```
Admittedly, these aren’t satisfactory so... |
Usually, when a user enters invalid data the program gives the user another chance, or chances,
until valid data are supplied. |
We’ll see how to do this soon.
Nevertheless, simple bounds checking is a good start!
-----
###### Comprehension check
1. |
Can you use De Morgan’s Laws (see: Boolean expressions) to
rewrite the bounds checking above?
2. |
If we were to do this, would we be checking to see if fingers is in
the desired range or outside the desired range?
3. |
If your answer to 2 (above) was outside the desired range, how
would you need to modify the program?
###### 8.7 Some string methods
Python provides us with many tools for manipulating strings. |
We won’t
introduce them all here, but instead we’ll demonstrate a few which we’ll
use in programming exercises, and then introduce more as we need them.
First, what is a string method? |
If you’ve ever programmed in Java or
C# or other OOP language, you may be familiar with methods. If not,
don’t fret, because the concept isn’t too difficult.
Strings are a type of object in Python. |
Consider what happens when
we ask Python what type the string “Mephistopheles” is.
```
>>> type('Mephistopheles')
<class 'str'>
```
What Python is telling us is that “Mephistopheles” is an object of type
```
str.
```
When the developers of Python defined the types str, int, float, bool,
_etc. |
they created classes corresponding to these different types of objects._
We won’t cover any object-oriented programming in this book, but you
can think of a class as a blueprint for creating objects of a given type.
We instantiate an object by making an assignment, for example
```
n = 42
```
creates an object of typ... |
The class definitions give Python
a blueprint for instantiating objects of these different types.
One of the things classes allow us to do is to define methods that are
part of the class definition and which are included with the objects along
with their data. |
Methods are nothing more than functions defined for a
class of objects which operate on the data of those objects.
Here’s an example. |
Let’s create a string object, s
```
>>> s = 'mephistopheles'
```
-----
Now, just like we can access individual members of the math module with the member (.) operator (for example, math.pi, math.sqrt(2),
```
math.sin(0.478), etc.) we can access string methods the same way!
```
For example, the capitalize() method... |
At some point in our code, we might have
something like this:
```
response = input('Do you wish to continue? |
Enter "y" '
'to continue or any other key to abort: ')
if response == 'y':
# This is where we'd continue whatever we were doing
else:
# This is where we'd abort
```
What would happen if the user were to enter upper case ‘Y’? |
Clearly the
user intends to continue, but the comparison
```
response == 'y'
```
would return False and the program would abort. |
That might make for
an unhappy user.
We could write
```
response = input('Do you wish to continue? |
Enter "y" '
'to continue or any other key to abort: ')
if response == 'y':
# This is where we'd continue whatever we were doing
elif response == 'Y':
# This is where we'd continue whatever we were doing
else:
# This is where we'd abort
```
or
```
response = input('Do you wish to continu... |
Enter "y" '
'to continue or any other key to abort: ')
if response == 'y' or response == 'Y':
# This is where we'd continue whatever we were doing
else:
# This is where we'd abort
```
Instead, we could use lower() and simplify our code!
```
response = input('Do you wish to continue? |
Enter "y" to '
'continue or any other key to abort: ')
if response.lower() == 'y':
# This is where we'd continue whatever we were doing
else:
# This is where we'd abort
```
-----
This code (above) behaves the same whether the user enters ‘y’ or ‘Y’,
because we convert to lower case before per... |
This
is one example of an application for string methods.
Another might be dealing with users that have the CAPS LOCK key
on.
```
name = input('Please enter your name: ')
# Now what if the user enters: 'EGBERT'?
# We can fix that:
name = name.capitalize()
# Now name is 'Egbert'
```
There are lots of uses.
#... |
Decision trees are commonly used for species identification.[5]_
Here’s an example:
**Figure 8.1: Decision tree for fruit**
Here, we start on the left and move toward the right, making decisions
along the way. |
Notice that at each branching point we have two branches.
So, for example, to reach “watermelon, cantaloupe”, we make the
decisions: soft inside, small seeds, thick skin, and unsegmented. |
To reach
5If you’ve had a course in biology, you may have heard of a cladogram for
representing taxonomic relationships of organisms. A cladogram is a kind of decision
[tree. |
If you’re curious, see: https://en.wikipedia.org/wiki/Cladogram and similar](https://en.wikipedia.org/wiki/Cladogram)
applications.
-----
“peach”, we’d have to have made the decisions: soft inside, pit or stone,
and fuzzy.
How do we encode these decision points? |
One way is to treat them as
yes or no questions. So if we ask “Is the fruit soft inside?” then we have
a yes or no answer. |
If the answer is “no”, then we know the fruit is not
soft inside and thus must be hard inside (like a walnut or almond).
Here’s a snippet of Python code, demonstrating a single question:
```
response = input('Is the fruit soft inside? |
y/n ')
if response == 'y':
# we know the fruit is soft inside
# ...
else:
# we know the fruit is hard inside
# ...
```
We can write a program that implements this decision tree by using
multiple, nested if statements.
```
"""
CS 1210
Decision tree for fruit identification
"""
response... |
y/n ')
if response.lower() == 'y':
# soft inside
response = input('Does it have small seeds? |
y/n ')
if response.lower() == 'y':
# small seeds
response = input('Does it have a thin skin? |
y/n ')
if response.lower() == 'y':
# thin skin
print("Tomato")
else:
# thick skin
response = input('Is it segmented? |
y/n ')
if response.lower() == 'y':
# segmented
print("Orange or lemon")
else:
# unsegmented
print("Watermelon or cantaloupe")
else:
# pit or stone
response = input('Is it fuzzy? |
y/n ')
if response.lower() == 'y':
# segmented
print("Peach")
else:
```
-----
```
# unsegmented
print("Plum")
else:
# hard inside
print("Walnut or almond")
###### Comprehension check
```
1. |
In the decision tree above, Figure 8.1, which decisions lead to plum?
(There are three.)
2. |
Revisit Section 8.4 and draw decision trees for the code examples
shown.
###### 8.9 Exercises
**Exercise 01**
Evaluate the result of the following, given that we have:
```
a = True
b = False
c = True
```
Do these on paper first, then check your answers in the Python shell.
1. |
a or b and c
2. a and b or c
3. a and b and c
4. not a or not b or c
5. |
not (a and b)
**Exercise 02**
Evaluate the result of the following, given that we have:
```
a = 1
b = 'pencil'
c = 'pen'
d = 'crayon'
```
Do these on paper first, then check your answers in the Python shell.
Some of these may surprise you!
1. |
a == b
2. b > c
3. b > d or a < 5
4. a != c
5. d == 'rabbit'
6. c < d or b > d
7. a and b < d
-----
8. (a == b) and (b != c)
9. (a and b) and (b < c)
10. |
not (a and b and c and d)
Ask yourself, what does it mean for 'crayon' to be less than 'pencil'?
How would you interpret this? |
Ask yourself, what’s going on when an
expression like 0 or 'crayon' is evaluated?
**Exercise 03**
Complete the following if statements so that they print the correct message. |
Notice that there are blank spaces in the code that you should
complete. |
You may assume we have three variables, with string values
assigned: cheese, blankets, toast, for example,
```
cheese = 'runny'
```
1. |
Cheese is smelly and blankets are warm!
```
if cheese == 'smelly' and :
print('Cheese is smelly and blankets are warm!')
```
2. Blankets are warm and toast is not pickled. |
Hint: use not or !=
```
if blankets :
print('Blankets are warm but toast is not pickled.')
```
3. |
Toast is yummy and so is cheese!
```
if :
print('Toast is yummy and so is cheese!')
```
4. |
Either toast is yummy or toast is green (or maybe both).
```
if :
print('Either toast is yummy or toast is green '
'(or maybe both).')
```
-----
**Exercise 04**
What is printed at the console for each of the following?
1.
```
>>> 'HELLO'.capitalize()
```
2.
```
>>> s = 'HoverCraft'
>>> s.lower... |
If we have four
possible outcomes, then our tree must have three branching points.
a. |
If we have eight possible outcomes in a decision tree, and decisions
are binary, how many branching points must we have?
b. What about 16?
c. |
Can you find a formula that calculates the number of branching
points given the number of outcomes? |
(OK if you can’t, so don’t
sweat it.)
-----
#### Chapter 9
### Structure, development, and testing
It’s important to be methodical when programming, and in this chapter
we’ll see how best to structure your Python code. |
Following this structure
takes much of the guesswork out of programming. Many questions about
where certain elements of your program belong are already answered for
you. |
What’s presented here is based on common (indeed nearly universal)
practice for professionally written code.
We’ll also learn a little bit about how to proceed when writing code
(that is, in small, incremental steps), how to test your code, how to use
_assertions, and what to do about the inevitable bugs._
**Learning ... |
But again, this is not the Python way._
Here’s how things work in Python. Python has what is called the top_level code environment. |
When a program is executed in this environment_
(which is what happens when you run your code within your IDE or
from the command line), there’s a special variable __name__ which is
automatically set to the value '__main__'.[1] `'__main__' is the name of`
the environment in which top-level code is run.
So if we wish to... |
It will *not* be executed if
# this module is imported.
r = float(input('Enter a non-negative real number: '))
if r >= 0:
c = circumference(r)
print(f'The circumference of a circle of radius '
f'{r:,.3f} is {c:,.3f}.')
else:
print(f'I asked for a non-negative number, ... |
If we were to run this program
from our IDE or from the command line with
```
$ python circle.py
```
Python would read the file, would see that we’re executing it, and thus
would set __name__ equal to '__main__'. |
Then, after reading the definition
of the function circumference(r_), it would reach the if statement,
1Some other programming languages refer to the top-level as the entry point.
```
'__main__' is the name of a Python program’s entry point.
```
-----
```
if __name__ == '__main__':
```
This condition evaluates t... |
So it would prompt the user for a radius,
and then check for valid input and return an appropriate response.
###### Another simple demonstration
Consider this Python program
```
"""
tlce.py (top-level code environment)
Another program to demonstrate the significance
of __name__ and __main__.
"""
print(__n... |
Then, try running this program from within your IDE or from
the command line. What will it print when you run it? |
It should print
```
__main__
Hello World!
```
So, you see, when we run a program in Python, Python sets the value
of the variable __name__ to the string '__main__', and then, when the
program performs the comparison __name__ == '__main__' this evaluates
to True, and the code within the if is executed.
###### What... |
What is printed? This program
should print
-----
```
tlce
```
So, if we import tlce then Python sets __name__ equal to 'tlce', and the
body of the if is never executed.
Why would we do this? |
One reason is that we can write functions
in one module, and import the module without executing any of the
module’s code, but make the functions available to us. Sound familiar?
It should. |
Consider what happens when we import the math module.
Nothing is executed, but now we have math.pi, math.sqrt(), math.sin(),
_etc. |
available to us._
###### A complete example
Earlier we created a program which, given some radius, 𝑟, provided by the
user, calculated the circumference, diameter, surface area, and volume of
a sphere of radius 𝑟. |
Here it is, with some minor modifications, notably
the addition of the check on the value of __name__.
```
"""
Sphere calculator (sphere.py)
Prompts the user for some radius, r, and then prints
the circumference, diameter, surface area, and volume
of a sphere with this radius.
"""
import math
def circum... |
But it’s not a stretch to see that we might want to use these
functions somewhere else!
Let’s say we’re manufacturing yoga balls—those inflatable balls that
people use for certain exercises requiring balance. |
We’d want to know
how much plastic we’d need to manufacture some number of balls. |
Say
our yoga balls are 33 centimeters in radius when inflated, and that we
want the thickness of the balls to be 0.1 centimeter.
In order to complete this calculation, we’ll need to calculate volume.
Why reinvent the wheel? |
We’ve already written a function to do this!
Let’s import sphere.py and use the function provided by this module.
```
"""
Yoga ball material requirements
"""
import sphere
# sphere.py must be in the same directory for this to work
RADIUS_CM = 33
THICKNESS_CM = 0.1
VINYL_G_PER_CC = 0.95
G_PER_KG = 1000... |
"))
outer = sphere.volume(RADIUS_CM)
inner = sphere.volume(RADIUS_CM - THICKNESS_CM)
material_per_ball = outer - inner
total_material = balls * material_per_ball
total_material_by_weight
= total_material / VINYL_G_PER_CC / G_PER_KG
print(f"To make {balls} balls, you will need "
... |
We’ve imported sphere so we can use its functions. |
When we import
```
sphere, __name__ (for sphere) takes on the value sphere so the code under
if __name__ == '__main__' isn’t executed!
```
This allows us to have our cake (a program that calculates diameter,
circumference, surface area, and volume of a sphere) and eat it too (by
-----
allowing imports and code reus... |
How cool is that?
###### What’s up with the funny names?
These funny names __name__ and '__main__' are called dunders. Dunder
is short for double underscore. |
This is a naming convention that Python
uses to set special variables, methods, and functions apart from the typical names programmers use for variables, methods, and functions they
define.
###### 9.2 Program structure
There is an order to things, and programs are no different. |
Your Python
code should follow this general layout:
1. docstring
2. imports (if any)
3. constants (if any)
4. |
function definitions (if any)
… and then, nested under if __name__ == '__main__':, all the rest of
your code. |
Here’s an example:
```
"""
A docstring, delimited by triple double-quotes,
which includes your name and a brief description
of your program.
"""
import foo # imports (if any)
MEGACYCLES_PER_FROMBULATION = 133 # constants (if any)
# Functions which you define...
def f(x_):
return 2 * x_ + 1
def g... |
This is a struc
-----
tured, step-by-step approach to writing software. This approach has long
been used to make the process of building complex programs more reliable. |
Even if you’re not undertaking a large-scale software development
project, this approach can be fruitful. |
Moreover, decomposing problems
into small portions or components can help reduce the complexity of the
task you’re working on at any given time.
Here’s an example. |
Let’s say we want to write a program that prompts
the user for mass and velocity and calculates the resulting kinetic energy.
If you haven’t had a course in physics before, don’t sweat it—the formula
is rather simple.
𝐾𝑒 = [1]2 [𝑚𝑣][2]
where 𝐾𝑒 is kinetic energy in Joules, 𝑚 is mass in kg, and 𝑣 is velocity
i... |
The first step might be
to sketch out what needs to happen with comments.[2]
```
"""
Kinetic Energy Calculator
Egbert Porcupine <egbert.porcupine@uvm.edu>
CS 1210
"""
# Step 1: Prompt user for mass in kg and save result
# Step 2: Prompt user for velocity in m / s and save result
# Step 3: Calculate kine... |
Now you run your code—yes,
it’s incomplete, but you decide to run it to confirm that the first step is
correctly implemented.
```
Enter mass in kg: 72.1
72.1
```
So that works as expected. |
Now you decide you can move on to step 2.
```
"""
Kinetic Energy Calculator
Egbert Porcupine <egbert.porcupine@uvm.edu>
CS 1210
"""
# Step 1: Prompt user for mass in kg and convert
# input to float and save result
mass = float(input('Enter mass in kg: '))
print(mass)
# Step 2: Prompt user for veloci... |
Now it’s time to perform the calculation of kinetic
energy.
```
"""
Kinetic Energy Calculator
Egbert Porcupine <egbert.porcupine@uvm.edu>
CS 1210
"""
# Step 1: Prompt user for mass in kg and convert
# input to float and save result
mass = float(input('Enter mass in kg: '))
print(mass)
# Step 2: Prom... |
Then you
decide to focus on printing a pretty result. |
You know you want to use
format specifiers, but you don’t want to fuss with that quite yet, so you
start with something simple (but not very pretty).
```
"""
Kinetic Energy Calculator
Egbert Porcupine <egbert.porcupine@uvm.edu>
CS 1210
"""
# Step 1: Prompt user for mass in kg and convert
# input to float ... |
That’s not hard to fix, and since you know the other
```
code is working OK you don’t need to touch it.
Here’s the fix:
```
"""
Kinetic Energy Calculator
Egbert Porcupine <egbert.porcupine@uvm.edu>
CS 1210
"""
# Step 1: Prompt user for mass in kg and convert input
# to float and save result
mass = floa... |
Everything else is working!
```
"""
Kinetic Energy Calculator
Egbert Porcupine <egbert.porcupine@uvm.edu>
CS 1210
"""
# Step 1: Prompt user for mass in kg and convert input
# to float and save result
mass = float(input('Enter mass in kg: '))
# Step 2: Prompt user for velocity in m / s and convert
# ... |
We started with
comments as placeholder / reminders, and then built up the program one
step at a time, testing along the way. |
Using this approach can make the
whole process easier by decomposing the problem into small, manageable,
bite-sized (or should I say “byte-sized”?) chunks. |
That’s incremental development.
###### 9.4 Testing your code
It’s important to test your code. |
In fact one famous dictum of programming is:
If it hasn’t been tested, it’s broken.
When writing code, try to anticipate odd or non-conforming input,
and then test your program to see how it handles such input.
3If you’re curious about how the pros do iterative and incremental development,
[see the Wikipedia article... |
Obviously, with larger programs this could get unwieldy,
but for small programs with few branches, it’s not unreasonable to try
each branch.
###### Some examples
Let’s say we had written a program that is intended to take pressure in
pounds per square inch (psi) and convert this to bars. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.