Mystr python world for i in range len mystr print i mystr i end

Last update on August 19 2022 21:51:42 [UTC/GMT +8 hours]

Python String: Exercise-4 with Solution

Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.

Sample Solution:-

Python Code:

def change_char[str1]:
  char = str1[0]
  str1 = str1.replace[char, '$']
  str1 = char + str1[1:]

  return str1

print[change_char['restart']]

Sample Output:

resta$t

Flowchart:


Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code [and comments] through Disqus.

Previous: Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.
Next: Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Python: Tips of the Day

Getting min/max from iterable [with/without specific function]:

# Getting maximum from iterable
>>> a = [1, 2, -3]
>>> max[a]
2

# Getting maximum from iterable
>>> min[a]
1

# Bot min/max has key value to allow to get maximum by appliing function
>>> max[a,key=abs]
3

  • Exercises: Weekly Top 16 Most Popular Topics
  • SQL Exercises, Practice, Solution - JOINS
  • SQL Exercises, Practice, Solution - SUBQUERIES
  • JavaScript basic - Exercises, Practice, Solution
  • Java Array: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : Conditional Statement
  • HR Database - SORT FILTER: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : String
  • Python Data Types: Dictionary - Exercises, Practice, Solution
  • Python Programming Puzzles - Exercises, Practice, Solution
  • C++ Array: Exercises, Practice, Solution
  • JavaScript conditional statements and loops - Exercises, Practice, Solution
  • C# Sharp Basic Algorithm: Exercises, Practice, Solution
  • Python Lambda - Exercises, Practice, Solution
  • Python Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation

Python Fundamentals

Overview

Teaching: 20 min
Exercises: 10 min

Questions

  • What basic data types can I work with in Python?

  • How can I create a new variable in Python?

  • How do I use a function?

  • Can I change the value associated with a variable after I create it?

Objectives

  • Assign values to variables.

Variables

Any Python interpreter can be used as a calculator:

This is great but not very interesting. To do anything useful with data, we need to assign its value to a variable. In Python, we can assign a value to a variable, using the equals sign =. For example, we can track the weight of a patient who weighs 60 kilograms by assigning the value 60 to a variable weight_kg:

From now on, whenever we use weight_kg, Python will substitute the value we assigned to it. In layperson’s terms, a variable is a name for a value.

In Python, variable names:

  • can include letters, digits, and underscores
  • cannot start with a digit
  • are case sensitive.

This means that, for example:

  • weight0 is a valid variable name, whereas 0weight is not
  • weight and Weight are different variables

Types of data

Python knows various types of data. Three common ones are:

  • integer numbers
  • floating point numbers, and
  • strings.

In the example above, variable weight_kg has an integer value of 60. If we want to more precisely track the weight of our patient, we can use a floating point value by executing:

To create a string, we add single or double quotes around some text. To identify and track a patient throughout our study, we can assign each person a unique identifier by storing it in a string:

Using Variables in Python

Once we have data stored with variable names, we can make use of it in calculations. We may want to store our patient’s weight in pounds as well as kilograms:

weight_lb = 2.2 * weight_kg

We might decide to add a prefix to our patient identifier:

patient_id = 'inflam_' + patient_id

Built-in Python functions

To carry out common tasks with data and variables in Python, the language provides us with several built-in functions. To display information to the screen, we use the print function:

print[weight_lb]
print[patient_id]

When we want to make use of a function, referred to as calling the function, we follow its name by parentheses. The parentheses are important: if you leave them off, the function doesn’t actually run! Sometimes you will include values or variables inside the parentheses for the function to use. In the case of print, we use the parentheses to tell the function what value we want to display. We will learn more about how functions work and how to create our own in later episodes.

We can display multiple things at once using only one print call:

print[patient_id, 'weight in kilograms:', weight_kg]

inflam_001 weight in kilograms: 60.3

We can also call a function inside of another function call. For example, Python has a built-in function called type that tells you a value’s data type:

print[type[60.3]]
print[type[patient_id]]



Moreover, we can do arithmetic with variables right inside the print function:

print['weight in pounds:', 2.2 * weight_kg]

The above command, however, did not change the value of weight_kg:

To change the value of the weight_kg variable, we have to assign weight_kg a new value using the equals = sign:

weight_kg = 65.0
print['weight in kilograms is now:', weight_kg]

weight in kilograms is now: 65.0

Variables as Sticky Notes

A variable in Python is analogous to a sticky note with a name written on it: assigning a value to a variable is like putting that sticky note on a particular value.

Using this analogy, we can investigate how assigning a value to one variable does not change values of other, seemingly related, variables. For example, let’s store the subject’s weight in pounds in its own variable:

# There are 2.2 pounds per kilogram
weight_lb = 2.2 * weight_kg
print['weight in kilograms:', weight_kg, 'and in pounds:', weight_lb]

weight in kilograms: 65.0 and in pounds: 143.0

Similar to above, the expression 2.2 * weight_kg is evaluated to 143.0, and then this value is assigned to the variable weight_lb [i.e. the sticky note weight_lb is placed on 143.0]. At this point, each variable is “stuck” to completely distinct and unrelated values.

Let’s now change weight_kg:

weight_kg = 100.0
print['weight in kilograms is now:', weight_kg, 'and weight in pounds is still:', weight_lb]

weight in kilograms is now: 100.0 and weight in pounds is still: 143.0

Since weight_lb doesn’t “remember” where its value comes from, it is not updated when we change weight_kg.

Check Your Understanding

What values do the variables mass and age have after each of the following statements? Test your answer by executing the lines.

mass = 47.5
age = 122
mass = mass * 2.0
age = age - 20

Solution

`mass` holds a value of 47.5, `age` does not exist
`mass` still holds a value of 47.5, `age` holds a value of 122
`mass` now has a value of 95.0, `age`'s value is still 122
`mass` still has a value of 95.0, `age` now holds 102

Sorting Out References

Python allows you to assign multiple values to multiple variables in one line by separating the variables and values with commas. What does the following program print out?

first, second = 'Grace', 'Hopper'
third, fourth = second, first
print[third, fourth]

Solution

Seeing Data Types

What are the data types of the following variables?

planet = 'Earth'
apples = 5
distance = 10.5

Solution

print[type[planet]]
print[type[apples]]
print[type[distance]]




Key Points

  • Basic data types in Python include integers, strings, and floating-point numbers.

  • Use variable = value to assign a value to a variable in order to record it in memory.

  • Variables are created on demand whenever a value is assigned to them.

  • Use print[something] to display the value of something.

  • Built-in functions are always available to use.

Analyzing Patient Data

Overview

Teaching: 40 min
Exercises: 20 min

Questions

  • How can I process tabular data files in Python?

Objectives

  • Explain what a library is and what libraries are used for.

  • Import a Python library and use the functions it contains.

  • Read tabular data from a file into a program.

  • Select individual values and subsections from data.

  • Perform operations on arrays of data.

Words are useful, but what’s more useful are the sentences and stories we build with them. Similarly, while a lot of powerful, general tools are built into Python, specialized tools built up from these basic units live in libraries that can be called upon when needed.

Loading data into Python

To begin processing the clinical trial inflammation data, we need to load it into Python. We can do that using a library called NumPy, which stands for Numerical Python. In general, you should use this library when you want to do fancy things with lots of numbers, especially if you have matrices or arrays. To tell Python that we’d like to start using NumPy, we need to import it:

Importing a library is like getting a piece of lab equipment out of a storage locker and setting it up on the bench. Libraries provide additional functionality to the basic Python package, much like a new piece of equipment adds functionality to a lab space. Just like in the lab, importing too many libraries can sometimes complicate and slow down your programs - so we only import what we need for each program.

Once we’ve imported the library, we can ask the library to read our data file for us:

numpy.loadtxt[fname='inflammation-01.csv', delimiter=',']

array[[[ 0.,  0.,  1., ...,  3.,  0.,  0.],
       [ 0.,  1.,  2., ...,  1.,  0.,  1.],
       [ 0.,  1.,  1., ...,  2.,  1.,  1.],
       ...,
       [ 0.,  1.,  1., ...,  1.,  1.,  1.],
       [ 0.,  0.,  0., ...,  0.,  2.,  0.],
       [ 0.,  0.,  1., ...,  1.,  1.,  0.]]]

The expression numpy.loadtxt[...] is a function call that asks Python to run the function loadtxt which belongs to the numpy library. The dot notation in Python is used most of all as an object attribute/property specifier or for invoking its method. object.property will give you the object.property value, object_name.method[] will invoke on object_name method.

As an example, John Smith is the John that belongs to the Smith family. We could use the dot notation to write his name smith.john, just as loadtxt is a function that belongs to the numpy library.

numpy.loadtxt has two parameters: the name of the file we want to read and the delimiter that separates values on a line. These both need to be character strings [or strings for short], so we put them in quotes.

Since we haven’t told it to do anything else with the function’s output, the notebook displays it. In this case, that output is the data we just loaded. By default, only a few rows and columns are shown [with ... to omit elements when displaying big arrays]. Note that, to save space when displaying NumPy arrays, Python does not show us trailing zeros, so 1.0 becomes 1..

Our call to numpy.loadtxt read our file but didn’t save the data in memory. To do that, we need to assign the array to a variable. In a similar manner to how we assign a single value to a variable, we can also assign an array of values to a variable using the same syntax. Let’s re-run numpy.loadtxt and save the returned data:

data = numpy.loadtxt[fname='inflammation-01.csv', delimiter=',']

This statement doesn’t produce any output because we’ve assigned the output to the variable data. If we want to check that the data have been loaded, we can print the variable’s value:

[[ 0.  0.  1. ...,  3.  0.  0.]
 [ 0.  1.  2. ...,  1.  0.  1.]
 [ 0.  1.  1. ...,  2.  1.  1.]
 ...,
 [ 0.  1.  1. ...,  1.  1.  1.]
 [ 0.  0.  0. ...,  0.  2.  0.]
 [ 0.  0.  1. ...,  1.  1.  0.]]

Now that the data are in memory, we can manipulate them. First, let’s ask what type of thing data refers to:

The output tells us that data currently refers to an N-dimensional array, the functionality for which is provided by the NumPy library. These data correspond to arthritis patients’ inflammation. The rows are the individual patients, and the columns are their daily inflammation measurements.

Data Type

A Numpy array contains one or more elements of the same type. The type function will only tell you that a variable is a NumPy array but won’t tell you the type of thing inside the array. We can find out the type of the data contained in the NumPy array.

This tells us that the NumPy array’s elements are floating-point numbers.

With the following command, we can see the array’s shape:

The output tells us that the data array variable contains 60 rows and 40 columns. When we created the variable data to store our arthritis data, we did not only create the array; we also created information about the array, called members or attributes. This extra information describes data in the same way an adjective describes a noun. data.shape is an attribute of data which describes the dimensions of data. We use the same dotted notation for the attributes of variables that we use for the functions in libraries because they have the same part-and-whole relationship.

If we want to get a single number from the array, we must provide an index in square brackets after the variable name, just as we do in math when referring to an element of a matrix. Our inflammation data has two dimensions, so we will need to use two indices to refer to one specific value:

print['first value in data:', data[0, 0]]

print['middle value in data:', data[30, 20]]

middle value in data: 13.0

The expression data[30, 20] accesses the element at row 30, column 20. While this expression may not surprise you, data[0, 0] might. Programming languages like Fortran, MATLAB and R start counting at 1 because that’s what human beings have done for thousands of years. Languages in the C family [including C++, Java, Perl, and Python] count from 0 because it represents an offset from the first value in the array [the second value is offset by one index from the first value]. This is closer to the way that computers represent arrays [if you are interested in the historical reasons behind counting indices from zero, you can read Mike Hoye’s blog post]. As a result, if we have an M×N array in Python, its indices go from 0 to M-1 on the first axis and 0 to N-1 on the second. It takes a bit of getting used to, but one way to remember the rule is that the index is how many steps we have to take from the start to get the item we want.

In the Corner

What may also surprise you is that when Python displays an array, it shows the element with index [0, 0] in the upper left corner rather than the lower left. This is consistent with the way mathematicians draw matrices but different from the Cartesian coordinates. The indices are [row, column] instead of [column, row] for the same reason, which can be confusing when plotting data.

Slicing data

An index like [30, 20] selects a single element of an array, but we can select whole sections as well. For example, we can select the first ten days [columns] of values for the first four patients [rows] like this:

[[ 0.  0.  1.  3.  1.  2.  4.  7.  8.  3.]
 [ 0.  1.  2.  1.  2.  1.  3.  2.  2.  6.]
 [ 0.  1.  1.  3.  3.  2.  6.  2.  5.  9.]
 [ 0.  0.  2.  0.  4.  2.  2.  1.  6.  7.]]

The slice 0:4 means, “Start at index 0 and go up to, but not including, index 4”. Again, the up-to-but-not-including takes a bit of getting used to, but the rule is that the difference between the upper and lower bounds is the number of values in the slice.

We don’t have to start slices at 0:

[[ 0.  0.  1.  2.  2.  4.  2.  1.  6.  4.]
 [ 0.  0.  2.  2.  4.  2.  2.  5.  5.  8.]
 [ 0.  0.  1.  2.  3.  1.  2.  3.  5.  3.]
 [ 0.  0.  0.  3.  1.  5.  6.  5.  5.  8.]
 [ 0.  1.  1.  2.  1.  3.  5.  3.  5.  8.]]

We also don’t have to include the upper and lower bound on the slice. If we don’t include the lower bound, Python uses 0 by default; if we don’t include the upper, the slice runs to the end of the axis, and if we don’t include either [i.e., if we use ‘:’ on its own], the slice includes everything:

small = data[:3, 36:]
print['small is:']
print[small]

The above example selects rows 0 through 2 and columns 36 through to the end of the array.

small is:
[[ 2.  3.  0.  0.]
 [ 1.  1.  0.  1.]
 [ 2.  2.  1.  1.]]

Analyzing data

NumPy has several useful functions that take an array as input to perform operations on its values. If we want to find the average inflammation for all patients on all days, for example, we can ask NumPy to compute data’s mean value:

mean is a function that takes an array as an argument.

Not All Functions Have Input

Generally, a function uses inputs to produce outputs. However, some functions produce outputs without needing any input. For example, checking the current time doesn’t require any input.

import time
print[time.ctime[]]

For functions that don’t take in any arguments, we still need parentheses [[]] to tell Python to go and do something for us.

Let’s use three other NumPy functions to get some descriptive values about the dataset. We’ll also use multiple assignment, a convenient Python feature that will enable us to do this all in one line.

maxval, minval, stdval = numpy.max[data], numpy.min[data], numpy.std[data]

print['maximum inflammation:', maxval]
print['minimum inflammation:', minval]
print['standard deviation:', stdval]

Here we’ve assigned the return value from numpy.max[data] to the variable maxval, the value from numpy.min[data] to minval, and so on.

maximum inflammation: 20.0
minimum inflammation: 0.0
standard deviation: 4.61383319712

Mystery Functions in IPython

How did we know what functions NumPy has and how to use them? If you are working in IPython or in a Jupyter Notebook, there is an easy way to find out. If you type the name of something followed by a dot, then you can use tab completion [e.g. type numpy. and then press Tab] to see a list of all functions and attributes that you can use. After selecting one, you can also add a question mark [e.g. numpy.cumprod?], and IPython will return an explanation of the method! This is the same as doing help[numpy.cumprod]. Similarly, if you are using the “plain vanilla” Python interpreter, you can type numpy. and press the Tab key twice for a listing of what is available. You can then use the help[] function to see an explanation of the function you’re interested in, for example: help[numpy.cumprod].

When analyzing data, though, we often want to look at variations in statistical values, such as the maximum inflammation per patient or the average inflammation per day. One way to do this is to create a new temporary array of the data we want, then ask it to do the calculation:

patient_0 = data[0, :] # 0 on the first axis [rows], everything on the second [columns]
print['maximum inflammation for patient 0:', numpy.max[patient_0]]

maximum inflammation for patient 0: 18.0

Everything in a line of code following the ‘#’ symbol is a comment that is ignored by Python. Comments allow programmers to leave explanatory notes for other programmers or their future selves.

We don’t actually need to store the row in a variable of its own. Instead, we can combine the selection and the function call:

print['maximum inflammation for patient 2:', numpy.max[data[2, :]]]

maximum inflammation for patient 2: 19.0

What if we need the maximum inflammation for each patient over all days [as in the next diagram on the left] or the average for each day [as in the diagram on the right]? As the diagram below shows, we want to perform the operation across an axis:

To support this functionality, most array functions allow us to specify the axis we want to work on. If we ask for the average across axis 0 [rows in our 2D example], we get:

print[numpy.mean[data, axis=0]]

[  0.           0.45         1.11666667   1.75         2.43333333   3.15
   3.8          3.88333333   5.23333333   5.51666667   5.95         5.9
   8.35         7.73333333   8.36666667   9.5          9.58333333
  10.63333333  11.56666667  12.35        13.25        11.96666667
  11.03333333  10.16666667  10.           8.66666667   9.15         7.25
   7.33333333   6.58333333   6.06666667   5.95         5.11666667   3.6
   3.3          3.56666667   2.48333333   1.5          1.13333333
   0.56666667]

As a quick check, we can ask this array what its shape is:

print[numpy.mean[data, axis=0].shape]

The expression [40,] tells us we have an N×1 vector, so this is the average inflammation per day for all patients. If we average across axis 1 [columns in our 2D example], we get:

print[numpy.mean[data, axis=1]]

[ 5.45   5.425  6.1    5.9    5.55   6.225  5.975  6.65   6.625  6.525
  6.775  5.8    6.225  5.75   5.225  6.3    6.55   5.7    5.85   6.55
  5.775  5.825  6.175  6.1    5.8    6.425  6.05   6.025  6.175  6.55
  6.175  6.35   6.725  6.125  7.075  5.725  5.925  6.15   6.075  5.75
  5.975  5.725  6.3    5.9    6.75   5.925  7.225  6.15   5.95   6.275  5.7
  6.1    6.825  5.975  6.725  5.7    6.25   6.4    7.05   5.9  ]

which is the average inflammation per patient across all days.

Slicing Strings

A section of an array is called a slice. We can take slices of character strings as well:

element = 'oxygen'
print['first three characters:', element[0:3]]
print['last three characters:', element[3:6]]

first three characters: oxy
last three characters: gen

What is the value of element[:4]? What about element[4:]? Or element[:]?

Solution

What is element[-1]? What is element[-2]?

Solution

Given those answers, explain what element[1:-1] does.

Solution

Creates a substring from index 1 up to [not including] the final index, effectively removing the first and last letters from ‘oxygen’

How can we rewrite the slice for getting the last three characters of element, so that it works even if we assign a different string to element? Test your solution with the following strings: carpentry, clone, hi.

Solution

element = 'oxygen'
print['last three characters:', element[-3:]]
element = 'carpentry'
print['last three characters:', element[-3:]]
element = 'clone'
print['last three characters:', element[-3:]]
element = 'hi'
print['last three characters:', element[-3:]]

last three characters: gen
last three characters: try
last three characters: one
last three characters: hi

Thin Slices

The expression element[3:3] produces an empty string, i.e., a string that contains no characters. If data holds our array of patient data, what does data[3:3, 4:4] produce? What about data[3:3, :]?

Solution

array[[], shape=[0, 0], dtype=float64]
array[[], shape=[0, 40], dtype=float64]

Stacking Arrays

Arrays can be concatenated and stacked on top of one another, using NumPy’s vstack and hstack functions for vertical and horizontal stacking, respectively.

import numpy

A = numpy.array[[[1,2,3], [4,5,6], [7, 8, 9]]]
print['A = ']
print[A]

B = numpy.hstack[[A, A]]
print['B = ']
print[B]

C = numpy.vstack[[A, A]]
print['C = ']
print[C]

A =
[[1 2 3]
 [4 5 6]
 [7 8 9]]
B =
[[1 2 3 1 2 3]
 [4 5 6 4 5 6]
 [7 8 9 7 8 9]]
C =
[[1 2 3]
 [4 5 6]
 [7 8 9]
 [1 2 3]
 [4 5 6]
 [7 8 9]]

Write some additional code that slices the first and last columns of A, and stacks them into a 3x2 array. Make sure to print the results to verify your solution.

Solution

A ‘gotcha’ with array indexing is that singleton dimensions are dropped by default. That means A[:, 0] is a one dimensional array, which won’t stack as desired. To preserve singleton dimensions, the index itself can be a slice or array. For example, A[:, :1] returns a two dimensional array with one singleton dimension [i.e. a column vector].

D = numpy.hstack[[A[:, :1], A[:, -1:]]]
print['D = ']
print[D]

Solution

An alternative way to achieve the same result is to use Numpy’s delete function to remove the second column of A.

D = numpy.delete[A, 1, 1]
print['D = ']
print[D]

Change In Inflammation

The patient data is longitudinal in the sense that each row represents a series of observations relating to one individual. This means that the change in inflammation over time is a meaningful concept. Let’s find out how to calculate changes in the data contained in an array with NumPy.

The numpy.diff[] function takes an array and returns the differences between two successive values. Let’s use it to examine the changes each day across the first week of patient 3 from our inflammation dataset.

patient3_week1 = data[3, :7]
print[patient3_week1]

Calling numpy.diff[patient3_week1] would do the following calculations

[ 0 - 0, 2 - 0, 0 - 2, 4 - 0, 2 - 4, 2 - 2 ]

and return the 6 difference values in a new array.

numpy.diff[patient3_week1]

array[[ 0.,  2., -2.,  4., -2.,  0.]]

Note that the array of differences is shorter by one element [length 6].

When calling numpy.diff with a multi-dimensional array, an axis argument may be passed to the function to specify which axis to process. When applying numpy.diff to our 2D inflammation array data, which axis would we specify?

Solution

Since the row axis [0] is patients, it does not make sense to get the difference between two arbitrary patients. The column axis [1] is in days, so the difference is the change in inflammation – a meaningful concept.

If the shape of an individual data file is [60, 40] [60 rows and 40 columns], what would the shape of the array be after you run the diff[] function and why?

Solution

The shape will be [60, 39] because there is one fewer difference between columns than there are columns in the data.

How would you find the largest change in inflammation for each patient? Does it matter if the change in inflammation is an increase or a decrease?

Solution

By using the numpy.max[] function after you apply the numpy.diff[] function, you will get the largest difference between days.

numpy.max[numpy.diff[data, axis=1], axis=1]

array[[  7.,  12.,  11.,  10.,  11.,  13.,  10.,   8.,  10.,  10.,   7.,
         7.,  13.,   7.,  10.,  10.,   8.,  10.,   9.,  10.,  13.,   7.,
        12.,   9.,  12.,  11.,  10.,  10.,   7.,  10.,  11.,  10.,   8.,
        11.,  12.,  10.,   9.,  10.,  13.,  10.,   7.,   7.,  10.,  13.,
        12.,   8.,   8.,  10.,  10.,   9.,   8.,  13.,  10.,   7.,  10.,
         8.,  12.,  10.,   7.,  12.]]

If inflammation values decrease along an axis, then the difference from one element to the next will be negative. If you are interested in the magnitude of the change and not the direction, the numpy.absolute[] function will provide that.

Notice the difference if you get the largest absolute difference between readings.

numpy.max[numpy.absolute[numpy.diff[data, axis=1]], axis=1]

array[[ 12.,  14.,  11.,  13.,  11.,  13.,  10.,  12.,  10.,  10.,  10.,
        12.,  13.,  10.,  11.,  10.,  12.,  13.,   9.,  10.,  13.,   9.,
        12.,   9.,  12.,  11.,  10.,  13.,   9.,  13.,  11.,  11.,   8.,
        11.,  12.,  13.,   9.,  10.,  13.,  11.,  11.,  13.,  11.,  13.,
        13.,  10.,   9.,  10.,  10.,   9.,   9.,  13.,  10.,   9.,  10.,
        11.,  13.,  10.,  10.,  12.]]

Key Points

  • Import a library into a program using import libraryname.

  • Use the numpy library to work with arrays in Python.

  • The expression array.shape gives the shape of an array.

  • Use array[x, y] to select a single element from a 2D array.

  • Array indices start at 0, not 1.

  • Use low:high to specify a slice that includes the indices from low to high-1.

  • Use # some kind of explanation to add comments to programs.

  • Use numpy.mean[array], numpy.max[array], and numpy.min[array] to calculate simple statistics.

  • Use numpy.mean[array, axis=0] or numpy.mean[array, axis=1] to calculate statistics across the specified axis.

Visualizing Tabular Data

Overview

Teaching: 30 min
Exercises: 20 min

Questions

  • How can I visualize tabular data in Python?

  • How can I group several plots together?

Objectives

  • Plot simple graphs from data.

  • Plot multiple graphs in a single figure.

Visualizing data

The mathematician Richard Hamming once said, “The purpose of computing is insight, not numbers,” and the best way to develop insight is often to visualize data. Visualization deserves an entire lecture of its own, but we can explore a few features of Python’s matplotlib library here. While there is no official plotting library, matplotlib is the de facto standard. First, we will import the pyplot module from matplotlib and use two of its functions to create and display a heat map of our data:

Episode Prerequisites

If you are continuing in the same notebook from the previous episode, you already have a data variable and have imported numpy. If you are starting a new notebook at this point, you need the following two lines:

import numpy
data = numpy.loadtxt[fname='inflammation-01.csv', delimiter=',']

import matplotlib.pyplot
image = matplotlib.pyplot.imshow[data]
matplotlib.pyplot.show[]

Each row in the heat map corresponds to a patient in the clinical trial dataset, and each column corresponds to a day in the dataset. Blue pixels in this heat map represent low values, while yellow pixels represent high values. As we can see, the general number of inflammation flare-ups for the patients rises and falls over a 40-day period.

So far so good as this is in line with our knowledge of the clinical trial and Dr. Maverick’s claims:

  • the patients take their medication once their inflammation flare-ups begin
  • it takes around 3 weeks for the medication to take effect and begin reducing flare-ups
  • and flare-ups appear to drop to zero by the end of the clinical trial.

Now let’s take a look at the average inflammation over time:

ave_inflammation = numpy.mean[data, axis=0]
ave_plot = matplotlib.pyplot.plot[ave_inflammation]
matplotlib.pyplot.show[]

Here, we have put the average inflammation per day across all patients in the variable ave_inflammation, then asked matplotlib.pyplot to create and display a line graph of those values. The result is a reasonably linear rise and fall, in line with Dr. Maverick’s claim that the medication takes 3 weeks to take effect. But a good data scientist doesn’t just consider the average of a dataset, so let’s have a look at two other statistics:

max_plot = matplotlib.pyplot.plot[numpy.max[data, axis=0]]
matplotlib.pyplot.show[]

min_plot = matplotlib.pyplot.plot[numpy.min[data, axis=0]]
matplotlib.pyplot.show[]

The maximum value rises and falls linearly, while the minimum seems to be a step function. Neither trend seems particularly likely, so either there’s a mistake in our calculations or something is wrong with our data. This insight would have been difficult to reach by examining the numbers themselves without visualization tools.

Grouping plots

You can group similar plots in a single figure using subplots. This script below uses a number of new commands. The function matplotlib.pyplot.figure[] creates a space into which we will place all of our plots. The parameter figsize tells Python how big to make this space. Each subplot is placed into the figure using its add_subplot method. The add_subplot method takes 3 parameters. The first denotes how many total rows of subplots there are, the second parameter refers to the total number of subplot columns, and the final parameter denotes which subplot your variable is referencing [left-to-right, top-to-bottom]. Each subplot is stored in a different variable [axes1, axes2, axes3]. Once a subplot is created, the axes can be titled using the set_xlabel[] command [or set_ylabel[]]. Here are our three plots side by side:

import numpy
import matplotlib.pyplot

data = numpy.loadtxt[fname='inflammation-01.csv', delimiter=',']

fig = matplotlib.pyplot.figure[figsize=[10.0, 3.0]]

axes1 = fig.add_subplot[1, 3, 1]
axes2 = fig.add_subplot[1, 3, 2]
axes3 = fig.add_subplot[1, 3, 3]

axes1.set_ylabel['average']
axes1.plot[numpy.mean[data, axis=0]]

axes2.set_ylabel['max']
axes2.plot[numpy.max[data, axis=0]]

axes3.set_ylabel['min']
axes3.plot[numpy.min[data, axis=0]]

fig.tight_layout[]

matplotlib.pyplot.savefig['inflammation.png']
matplotlib.pyplot.show[]

The call to loadtxt reads our data, and the rest of the program tells the plotting library how large we want the figure to be, that we’re creating three subplots, what to draw for each one, and that we want a tight layout. [If we leave out that call to fig.tight_layout[], the graphs will actually be squeezed together more closely.]

The call to savefig stores the plot as a graphics file. This can be a convenient way to store your plots for use in other documents, web pages etc. The graphics format is automatically determined by Matplotlib from the file name ending we specify; here PNG from ‘inflammation.png’. Matplotlib supports many different graphics formats, including SVG, PDF, and JPEG.

Importing libraries with shortcuts

In this lesson we use the import matplotlib.pyplot syntax to import the pyplot module of matplotlib. However, shortcuts such as import matplotlib.pyplot as plt are frequently used. Importing pyplot this way means that after the initial import, rather than writing matplotlib.pyplot.plot[...], you can now write plt.plot[...]. Another common convention is to use the shortcut import numpy as np when importing the NumPy library. We then can write np.loadtxt[...] instead of numpy.loadtxt[...], for example.

Some people prefer these shortcuts as it is quicker to type and results in shorter lines of code - especially for libraries with long names! You will frequently see Python code online using a pyplot function with plt, or a NumPy function with np, and it’s because they’ve used this shortcut. It makes no difference which approach you choose to take, but you must be consistent as if you use import matplotlib.pyplot as plt then matplotlib.pyplot.plot[...] will not work, and you must use plt.plot[...] instead. Because of this, when working with other people it is important you agree on how libraries are imported.

Plot Scaling

Why do all of our plots stop just short of the upper end of our graph?

Solution

Because matplotlib normally sets x and y axes limits to the min and max of our data [depending on data range]

If we want to change this, we can use the set_ylim[min, max] method of each ‘axes’, for example:

Update your plotting code to automatically set a more appropriate scale. [Hint: you can make use of the max and min methods to help.]

Solution

# One method
axes3.set_ylabel['min']
axes3.plot[numpy.min[data, axis=0]]
axes3.set_ylim[0,6]

Solution

# A more automated approach
min_data = numpy.min[data, axis=0]
axes3.set_ylabel['min']
axes3.plot[min_data]
axes3.set_ylim[numpy.min[min_data], numpy.max[min_data] * 1.1]

Drawing Straight Lines

In the center and right subplots above, we expect all lines to look like step functions because non-integer value are not realistic for the minimum and maximum values. However, you can see that the lines are not always vertical or horizontal, and in particular the step function in the subplot on the right looks slanted. Why is this?

Solution

Because matplotlib interpolates [draws a straight line] between the points. One way to do avoid this is to use the Matplotlib drawstyle option:

import numpy
import matplotlib.pyplot

data = numpy.loadtxt[fname='inflammation-01.csv', delimiter=',']

fig = matplotlib.pyplot.figure[figsize=[10.0, 3.0]]

axes1 = fig.add_subplot[1, 3, 1]
axes2 = fig.add_subplot[1, 3, 2]
axes3 = fig.add_subplot[1, 3, 3]

axes1.set_ylabel['average']
axes1.plot[numpy.mean[data, axis=0], drawstyle='steps-mid']

axes2.set_ylabel['max']
axes2.plot[numpy.max[data, axis=0], drawstyle='steps-mid']

axes3.set_ylabel['min']
axes3.plot[numpy.min[data, axis=0], drawstyle='steps-mid']

fig.tight_layout[]

matplotlib.pyplot.show[]

Make Your Own Plot

Create a plot showing the standard deviation [numpy.std] of the inflammation data for each day across all patients.

Solution

std_plot = matplotlib.pyplot.plot[numpy.std[data, axis=0]]
matplotlib.pyplot.show[]

Moving Plots Around

Modify the program to display the three plots on top of one another instead of side by side.

Solution

import numpy
import matplotlib.pyplot

data = numpy.loadtxt[fname='inflammation-01.csv', delimiter=',']

# change figsize [swap width and height]
fig = matplotlib.pyplot.figure[figsize=[3.0, 10.0]]

# change add_subplot [swap first two parameters]
axes1 = fig.add_subplot[3, 1, 1]
axes2 = fig.add_subplot[3, 1, 2]
axes3 = fig.add_subplot[3, 1, 3]

axes1.set_ylabel['average']
axes1.plot[numpy.mean[data, axis=0]]

axes2.set_ylabel['max']
axes2.plot[numpy.max[data, axis=0]]

axes3.set_ylabel['min']
axes3.plot[numpy.min[data, axis=0]]

fig.tight_layout[]

matplotlib.pyplot.show[]

Key Points

  • Use the pyplot module from the matplotlib library for creating simple visualizations.

Storing Multiple Values in Lists

Overview

Teaching: 30 min
Exercises: 15 min

Questions

  • How can I store many values together?

Objectives

  • Explain what a list is.

  • Create and index lists of simple values.

  • Change the values of individual elements

  • Append values to an existing list

  • Reorder and slice list elements

  • Create and manipulate nested lists

In the previous episode, we analyzed a single file of clinical trial inflammation data. However, after finding some peculiar and potentially suspicious trends in the trial data we ask Dr. Maverick if they have performed any other clinical trials. Surprisingly, they say that they have and provide us with 11 more CSV files for a further 11 clinical trials they have undertaken since the initial trial.

Our goal now is to process all the inflammation data we have, which means that we still have eleven more files to go!

The natural first step is to collect the names of all the files that we have to process. In Python, a list is a way to store multiple values together. In this episode, we will learn how to store multiple values in a list as well as how to work with lists.

Python lists

Unlike NumPy arrays, lists are built into the language so we do not have to load a library to use them. We create a list by putting values inside square brackets and separating the values with commas:

odds = [1, 3, 5, 7]
print['odds are:', odds]

We can access elements of a list using indices – numbered positions of elements in the list. These positions are numbered starting at 0, so the first element has an index of 0.

print['first element:', odds[0]]
print['last element:', odds[3]]
print['"-1" element:', odds[-1]]

first element: 1
last element: 7
"-1" element: 7

Yes, we can use negative numbers as indices in Python. When we do so, the index -1 gives us the last element in the list, -2 the second to last, and so on. Because of this, odds[3] and odds[-1] point to the same element here.

There is one important difference between lists and strings: we can change the values in a list, but we cannot change individual characters in a string. For example:

names = ['Curie', 'Darwing', 'Turing']  # typo in Darwin's name
print['names is originally:', names]
names[1] = 'Darwin'  # correct the name
print['final value of names:', names]

names is originally: ['Curie', 'Darwing', 'Turing']
final value of names: ['Curie', 'Darwin', 'Turing']

works, but:

name = 'Darwin'
name[0] = 'd'

---------------------------------------------------------------------------
TypeError                                 Traceback [most recent call last]
 in []
      1 name = 'Darwin'
----> 2 name[0] = 'd'

TypeError: 'str' object does not support item assignment

does not.

Ch-Ch-Ch-Ch-Changes

Data which can be modified in place is called mutable, while data which cannot be modified is called immutable. Strings and numbers are immutable. This does not mean that variables with string or number values are constants, but when we want to change the value of a string or number variable, we can only replace the old value with a completely new value.

Lists and arrays, on the other hand, are mutable: we can modify them after they have been created. We can change individual elements, append new elements, or reorder the whole list. For some operations, like sorting, we can choose whether to use a function that modifies the data in-place or a function that returns a modified copy and leaves the original unchanged.

Be careful when modifying data in-place. If two variables refer to the same list, and you modify the list value, it will change for both variables!

salsa = ['peppers', 'onions', 'cilantro', 'tomatoes']
my_salsa = salsa        #  100:
    print['greater']
else:
    print['not greater']
print['done']

The second line of this code uses the keyword if to tell Python that we want to make a choice. If the test that follows the if statement is true, the body of the if [i.e., the set of lines indented underneath it] is executed, and “greater” is printed. If the test is false, the body of the else is executed instead, and “not greater” is printed. Only one or the other is ever executed before continuing on with program execution to print “done”:

Conditional statements don’t have to include an else. If there isn’t one, Python simply does nothing if the test is false:

num = 53
print['before conditional...']
if num > 100:
    print[num, 'is greater than 100']
print['...after conditional']

before conditional...
...after conditional

We can also chain several tests together using elif, which is short for “else if”. The following Python code uses elif to print the sign of a number.

num = -3

if num > 0:
    print[num, 'is positive']
elif num == 0:
    print[num, 'is zero']
else:
    print[num, 'is negative']

Note that to test for equality we use a double equals sign == rather than a single equals sign = which is used to assign values.

Comparing in Python

Along with the > and == operators we have already used for comparing values in our conditionals, there are a few more options to know about:

  • >: greater than
  • =: greater than or equal to
  • 0] and [-1 >= 0]: print['both parts are true'] else: print['at least one part is false']

    at least one part is false
    

    while or is true if at least one part is true:

    if [1 = 0]:
        print['at least one test is true']
    

    at least one test is true
    

    True and False

    True and False are special words in Python called booleans, which represent truth values. A statement such as 1 < 0 returns the value False, while -1 < 0 returns the value True.

    Checking our Data

    Now that we’ve seen how conditionals work, we can use them to check for the suspicious features we saw in our inflammation data. We are about to use functions provided by the numpy module again. Therefore, if you’re working in a new Python session, make sure to load the module with:

    From the first couple of plots, we saw that maximum daily inflammation exhibits a strange behavior and raises one unit a day. Wouldn’t it be a good idea to detect such behavior and report it as suspicious? Let’s do that! However, instead of checking every single day of the study, let’s merely check if maximum inflammation in the beginning [day 0] and in the middle [day 20] of the study are equal to the corresponding day numbers.

    max_inflammation_0 = numpy.max[data, axis=0][0]
    max_inflammation_20 = numpy.max[data, axis=0][20]
    
    if max_inflammation_0 == 0 and max_inflammation_20 == 20:
        print['Suspicious looking maxima!']
    

    We also saw a different problem in the third dataset; the minima per day were all zero [looks like a healthy person snuck into our study]. We can also check for this with an elif condition:

    elif numpy.sum[numpy.min[data, axis=0]] == 0:
        print['Minima add up to zero!']
    

    And if neither of these conditions are true, we can use else to give the all-clear:

    Let’s test that out:

    data = numpy.loadtxt[fname='inflammation-01.csv', delimiter=',']
    
    max_inflammation_0 = numpy.max[data, axis=0][0]
    max_inflammation_20 = numpy.max[data, axis=0][20]
    
    if max_inflammation_0 == 0 and max_inflammation_20 == 20:
        print['Suspicious looking maxima!']
    elif numpy.sum[numpy.min[data, axis=0]] == 0:
        print['Minima add up to zero!']
    else:
        print['Seems OK!']
    

    Suspicious looking maxima!
    

    data = numpy.loadtxt[fname='inflammation-03.csv', delimiter=',']
    
    max_inflammation_0 = numpy.max[data, axis=0][0]
    max_inflammation_20 = numpy.max[data, axis=0][20]
    
    if max_inflammation_0 == 0 and max_inflammation_20 == 20:
        print['Suspicious looking maxima!']
    elif numpy.sum[numpy.min[data, axis=0]] == 0:
        print['Minima add up to zero!']
    else:
        print['Seems OK!']
    

    In this way, we have asked Python to do something different depending on the condition of our data. Here we printed messages in all cases, but we could also imagine not using the else catch-all so that messages are only printed when something is wrong, freeing us from having to manually examine every plot for features we’ve seen before.

    How Many Paths?

    Consider this code:

    if 4 > 5:
        print['A']
    elif 4 == 5:
        print['B']
    elif 4  5 and 4 == 5, are not true, but 4 < 5 is true.

What Is Truth?

True and False booleans are not the only values in Python that are true and false. In fact, any value can be used in an if or elif. After reading and running the code below, explain what the rule is for which values are considered true and which are considered false.

if '':
    print['empty string is true']
if 'word':
    print['word is true']
if []:
    print['empty list is true']
if [1, 2, 3]:
    print['non-empty list is true']
if 0:
    print['zero is true']
if 1:
    print['one is true']

That’s Not Not What I Meant

Sometimes it is useful to check whether some condition is not true. The Boolean operator not can do this explicitly. After reading and running the code below, write some if statements that use not to test the rule that you formulated in the previous challenge.

if not '':
    print['empty string is not true']
if not 'word':
    print['word is not true']
if not not True:
    print['not not True is true']

Close Enough

Write some conditions that print True if the variable a is within 10% of the variable b and False otherwise. Compare your implementation with your partner’s: do you get the same answer for all possible pairs of numbers?

Hint

There is a built-in function abs that returns the absolute value of a number:

Solution 1

a = 5
b = 5.1

if abs[a - b]  1 print['Again, temperature in Kelvin was:', temp_k]

NameError: name 'temp_k' is not defined

If you want to reuse the temperature in Kelvin after you have calculated it with fahr_to_kelvin, you can store the result of the function call in a variable:

temp_kelvin = fahr_to_kelvin[212.0]
print['temperature in Kelvin was:', temp_kelvin]

temperature in Kelvin was: 373.15

The variable temp_kelvin, being defined outside any function, is said to be global.

Inside a function, one can read the value of such global variables:

def print_temperatures[]:
  print['temperature in Fahrenheit was:', temp_fahr]
  print['temperature in Kelvin was:', temp_kelvin]

temp_fahr = 212.0
temp_kelvin = fahr_to_kelvin[temp_fahr]

print_temperatures[]

temperature in Fahrenheit was: 212.0
temperature in Kelvin was: 373.15

Tidying up

Now that we know how to wrap bits of code up in functions, we can make our inflammation analysis easier to read and easier to reuse. First, let’s make a visualize function that generates our plots:

def visualize[filename]:

    data = numpy.loadtxt[fname=filename, delimiter=',']

    fig = matplotlib.pyplot.figure[figsize=[10.0, 3.0]]

    axes1 = fig.add_subplot[1, 3, 1]
    axes2 = fig.add_subplot[1, 3, 2]
    axes3 = fig.add_subplot[1, 3, 3]

    axes1.set_ylabel['average']
    axes1.plot[numpy.mean[data, axis=0]]

    axes2.set_ylabel['max']
    axes2.plot[numpy.max[data, axis=0]]

    axes3.set_ylabel['min']
    axes3.plot[numpy.min[data, axis=0]]

    fig.tight_layout[]
    matplotlib.pyplot.show[]

and another function called detect_problems that checks for those systematics we noticed:

def detect_problems[filename]:

    data = numpy.loadtxt[fname=filename, delimiter=',']

    if numpy.max[data, axis=0][0] == 0 and numpy.max[data, axis=0][20] == 20:
        print['Suspicious looking maxima!']
    elif numpy.sum[numpy.min[data, axis=0]] == 0:
        print['Minima add up to zero!']
    else:
        print['Seems OK!']

Wait! Didn’t we forget to specify what both of these functions should return? Well, we didn’t. In Python, functions are not required to include a return statement and can be used for the sole purpose of grouping together pieces of code that conceptually do one thing. In such cases, function names usually describe what they do, e.g. visualize, detect_problems.

Notice that rather than jumbling this code together in one giant for loop, we can now read and reuse both ideas separately. We can reproduce the previous analysis with a much simpler for loop:

filenames = sorted[glob.glob['inflammation*.csv']]

for filename in filenames[:3]:
    print[filename]
    visualize[filename]
    detect_problems[filename]

By giving our functions human-readable names, we can more easily read and understand what is happening in the for loop. Even better, if at some later date we want to use either of those pieces of code again, we can do so in a single line.

Testing and Documenting

Once we start putting things in functions so that we can re-use them, we need to start testing that those functions are working correctly. To see how to do this, let’s write a function to offset a dataset so that it’s mean value shifts to a user-defined value:

def offset_mean[data, target_mean_value]:
    return [data - numpy.mean[data]] + target_mean_value

We could test this on our actual data, but since we don’t know what the values ought to be, it will be hard to tell if the result was correct. Instead, let’s use NumPy to create a matrix of 0’s and then offset its values to have a mean value of 3:

z = numpy.zeros[[2,2]]
print[offset_mean[z, 3]]

That looks right, so let’s try offset_mean on our real data:

data = numpy.loadtxt[fname='inflammation-01.csv', delimiter=',']
print[offset_mean[data, 0]]

[[-6.14875 -6.14875 -5.14875 ... -3.14875 -6.14875 -6.14875]
 [-6.14875 -5.14875 -4.14875 ... -5.14875 -6.14875 -5.14875]
 [-6.14875 -5.14875 -5.14875 ... -4.14875 -5.14875 -5.14875]
 ...
 [-6.14875 -5.14875 -5.14875 ... -5.14875 -5.14875 -5.14875]
 [-6.14875 -6.14875 -6.14875 ... -6.14875 -4.14875 -6.14875]
 [-6.14875 -6.14875 -5.14875 ... -5.14875 -5.14875 -6.14875]]

It’s hard to tell from the default output whether the result is correct, but there are a few tests that we can run to reassure us:

print['original min, mean, and max are:', numpy.min[data], numpy.mean[data], numpy.max[data]]
offset_data = offset_mean[data, 0]
print['min, mean, and max of offset data are:',
      numpy.min[offset_data],
      numpy.mean[offset_data],
      numpy.max[offset_data]]

original min, mean, and max are: 0.0 6.14875 20.0
min, mean, and and max of offset data are: -6.14875 2.84217094304e-16 13.85125

That seems almost right: the original mean was about 6.1, so the lower bound from zero is now about -6.1. The mean of the offset data isn’t quite zero — we’ll explore why not in the challenges — but it’s pretty close. We can even go further and check that the standard deviation hasn’t changed:

print['std dev before and after:', numpy.std[data], numpy.std[offset_data]]

std dev before and after: 4.61383319712 4.61383319712

Those values look the same, but we probably wouldn’t notice if they were different in the sixth decimal place. Let’s do this instead:

print['difference in standard deviations before and after:',
      numpy.std[data] - numpy.std[offset_data]]

difference in standard deviations before and after: -3.5527136788e-15

Again, the difference is very small. It’s still possible that our function is wrong, but it seems unlikely enough that we should probably get back to doing our analysis. We have one more task first, though: we should write some documentation for our function to remind ourselves later what it’s for and how to use it.

The usual way to put documentation in software is to add comments like this:

# offset_mean[data, target_mean_value]:
# return a new array containing the original data with its mean offset to match the desired value.
def offset_mean[data, target_mean_value]:
    return [data - numpy.mean[data]] + target_mean_value

There’s a better way, though. If the first thing in a function is a string that isn’t assigned to a variable, that string is attached to the function as its documentation:

def offset_mean[data, target_mean_value]:
    """Return a new array containing the original data
       with its mean offset to match the desired value."""
    return [data - numpy.mean[data]] + target_mean_value

This is better because we can now ask Python’s built-in help system to show us the documentation for the function:

Help on function offset_mean in module __main__:

offset_mean[data, target_mean_value]
    Return a new array containing the original data with its mean offset to match the desired value.

A string like this is called a docstring. We don’t need to use triple quotes when we write one, but if we do, we can break the string across multiple lines:

def offset_mean[data, target_mean_value]:
    """Return a new array containing the original data
       with its mean offset to match the desired value.

    Examples
    --------
    >>> offset_mean[[1, 2, 3], 0]
    array[[-1.,  0.,  1.]]
    """
    return [data - numpy.mean[data]] + target_mean_value

help[offset_mean]

Help on function offset_mean in module __main__:

offset_mean[data, target_mean_value]
    Return a new array containing the original data
       with its mean offset to match the desired value.

    Examples
    --------
    >>> offset_mean[[1, 2, 3], 0]
    array[[-1.,  0.,  1.]]

Defining Defaults

We have passed parameters to functions in two ways: directly, as in type[data], and by name, as in numpy.loadtxt[fname='something.csv', delimiter=',']. In fact, we can pass the filename to loadtxt without the fname=:

numpy.loadtxt['inflammation-01.csv', delimiter=',']

array[[[ 0.,  0.,  1., ...,  3.,  0.,  0.],
       [ 0.,  1.,  2., ...,  1.,  0.,  1.],
       [ 0.,  1.,  1., ...,  2.,  1.,  1.],
       ...,
       [ 0.,  1.,  1., ...,  1.,  1.,  1.],
       [ 0.,  0.,  0., ...,  0.,  2.,  0.],
       [ 0.,  0.,  1., ...,  1.,  1.,  0.]]]

but we still need to say delimiter=:

numpy.loadtxt['inflammation-01.csv', ',']

Traceback [most recent call last]:
  File "", line 1, in 
  File "/Users/username/anaconda3/lib/python3.6/site-packages/numpy/lib/npyio.py", line 1041, in loa
dtxt
    dtype = np.dtype[dtype]
  File "/Users/username/anaconda3/lib/python3.6/site-packages/numpy/core/_internal.py", line 199, in
_commastring
    newitem = [dtype, eval[repeats]]
  File "", line 1
    ,
    ^
SyntaxError: unexpected EOF while parsing

To understand what’s going on, and make our own functions easier to use, let’s re-define our offset_mean function like this:

def offset_mean[data, target_mean_value=0.0]:
    """Return a new array containing the original data
       with its mean offset to match the desired value, [0 by default].

    Examples
    --------
    >>> offset_mean[[1, 2, 3]]
    array[[-1.,  0.,  1.]]
    """
    return [data - numpy.mean[data]] + target_mean_value

The key change is that the second parameter is now written target_mean_value=0.0 instead of just target_mean_value. If we call the function with two arguments, it works as it did before:

test_data = numpy.zeros[[2, 2]]
print[offset_mean[test_data, 3]]

But we can also now call it with just one parameter, in which case target_mean_value is automatically assigned the default value of 0.0:

more_data = 5 + numpy.zeros[[2, 2]]
print['data before mean offset:']
print[more_data]
print['offset data:']
print[offset_mean[more_data]]

data before mean offset:
[[ 5.  5.]
 [ 5.  5.]]
offset data:
[[ 0.  0.]
 [ 0.  0.]]

This is handy: if we usually want a function to work one way, but occasionally need it to do something else, we can allow people to pass a parameter when they need to but provide a default to make the normal case easier. The example below shows how Python matches values to parameters:

def display[a=1, b=2, c=3]:
    print['a:', a, 'b:', b, 'c:', c]

print['no parameters:']
display[]
print['one parameter:']
display[55]
print['two parameters:']
display[55, 66]

no parameters:
a: 1 b: 2 c: 3
one parameter:
a: 55 b: 2 c: 3
two parameters:
a: 55 b: 66 c: 3

As this example shows, parameters are matched up from left to right, and any that haven’t been given a value explicitly get their default value. We can override this behavior by naming the value as we pass it in:

print['only setting the value of c']
display[c=77]

only setting the value of c
a: 1 b: 2 c: 77

With that in hand, let’s look at the help for numpy.loadtxt:

Help on function loadtxt in module numpy.lib.npyio:

loadtxt[fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, use
cols=None, unpack=False, ndmin=0, encoding='bytes']
    Load data from a text file.

    Each row in the text file must have the same number of values.

    Parameters
    ----------
...

There’s a lot of information here, but the most important part is the first couple of lines:

loadtxt[fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, use
cols=None, unpack=False, ndmin=0, encoding='bytes']

This tells us that loadtxt has one parameter called fname that doesn’t have a default value, and eight others that do. If we call the function like this:

numpy.loadtxt['inflammation-01.csv', ',']

then the filename is assigned to fname [which is what we want], but the delimiter string ',' is assigned to dtype rather than delimiter, because dtype is the second parameter in the list. However ',' isn’t a known dtype so our code produced an error message when we tried to run it. When we call loadtxt we don’t have to provide fname= for the filename because it’s the first item in the list, but if we want the ',' to be assigned to the variable delimiter, we do have to provide delimiter= for the second parameter since delimiter is not the second parameter in the list.

Readable functions

Consider these two functions:

def s[p]:
    a = 0
    for v in p:
        a += v
    m = a / len[p]
    d = 0
    for v in p:
        d += [v - m] * [v - m]
    return numpy.sqrt[d / [len[p] - 1]]

def std_dev[sample]:
    sample_sum = 0
    for value in sample:
        sample_sum += value

    sample_mean = sample_sum / len[sample]

    sum_squared_devs = 0
    for value in sample:
        sum_squared_devs += [value - sample_mean] * [value - sample_mean]

    return numpy.sqrt[sum_squared_devs / [len[sample] - 1]]

The functions s and std_dev are computationally equivalent [they both calculate the sample standard deviation], but to a human reader, they look very different. You probably found std_dev much easier to read and understand than s.

As this example illustrates, both documentation and a programmer’s coding style combine to determine how easy it is for others to read and understand the programmer’s code. Choosing meaningful variable names and using blank spaces to break the code into logical “chunks” are helpful techniques for producing readable code. This is useful not only for sharing code with others, but also for the original programmer. If you need to revisit code that you wrote months ago and haven’t thought about since then, you will appreciate the value of readable code!

Combining Strings

“Adding” two strings produces their concatenation: 'a' + 'b' is 'ab'. Write a function called fence that takes two parameters called original and wrapper and returns a new string that has the wrapper character at the beginning and end of the original. A call to your function should look like this:

print[fence['name', '*']]

Solution

def fence[original, wrapper]:
    return wrapper + original + wrapper

Return versus print

Note that return and print are not interchangeable. print is a Python function that prints data to the screen. It enables us, users, see the data. return statement, on the other hand, makes data visible to the program. Let’s have a look at the following function:

def add[a, b]:
    print[a + b]

Question: What will we see if we execute the following commands?

Solution

Python will first execute the function add with a = 7 and b = 3, and, therefore, print 10. However, because function add does not have a line that starts with return [no return “statement”], it will, by default, return nothing which, in Python world, is called None. Therefore, A will be assigned to None and the last line [print[A]] will print None. As a result, we will see:

Selecting Characters From Strings

If the variable s refers to a string, then s[0] is the string’s first character and s[-1] is its last. Write a function called outer that returns a string made up of just the first and last characters of its input. A call to your function should look like this:

Solution

def outer[input_string]:
    return input_string[0] + input_string[-1]

Rescaling an Array

Write a function rescale that takes an array as input and returns a corresponding array of values scaled to lie in the range 0.0 to 1.0. [Hint: If L and H are the lowest and highest values in the original array, then the replacement for a value v should be [v-L] / [H-L].]

Solution

def rescale[input_array]:
    L = numpy.min[input_array]
    H = numpy.max[input_array]
    output_array = [input_array - L] / [H - L]
    return output_array

Testing and Documenting Your Function

Run the commands help[numpy.arange] and help[numpy.linspace] to see how to use these functions to generate regularly-spaced values, then use those values to test your rescale function. Once you’ve successfully tested your function, add a docstring that explains what it does.

Solution

"""Takes an array as input, and returns a corresponding array scaled so
that 0 corresponds to the minimum and 1 to the maximum value of the input array.

Examples:
>>> rescale[numpy.arange[10.0]]
array[[ 0.        ,  0.11111111,  0.22222222,  0.33333333,  0.44444444,
       0.55555556,  0.66666667,  0.77777778,  0.88888889,  1.        ]]
>>> rescale[numpy.linspace[0, 100, 5]]
array[[ 0.  ,  0.25,  0.5 ,  0.75,  1.  ]]
"""

Defining Defaults

Rewrite the rescale function so that it scales data to lie between 0.0 and 1.0 by default, but will allow the caller to specify lower and upper bounds if they want. Compare your implementation to your neighbor’s: do the two functions always behave the same way?

Solution

def rescale[input_array, low_val=0.0, high_val=1.0]:
    """rescales input array values to lie between low_val and high_val"""
    L = numpy.min[input_array]
    H = numpy.max[input_array]
    intermed_array = [input_array - L] / [H - L]
    output_array = intermed_array * [high_val - low_val] + low_val
    return output_array

Variables Inside and Outside Functions

What does the following piece of code display when run — and why?

f = 0
k = 0

def f2k[f]:
    k = [[f - 32] * [5.0 / 9.0]] + 273.15
    return k

print[f2k[8]]
print[f2k[41]]
print[f2k[32]]

print[k]

Solution

259.81666666666666
278.15
273.15
0

k is 0 because the k inside the function f2k doesn’t know about the k defined outside the function. When the f2k function is called, it creates a local variable k. The function does not return any values and does not alter k outside of its local copy. Therefore the original value of k remains unchanged. Beware that a local k is created because f2k internal statements affect a new value to it. If k was only read, it would simply retrieve the global k value.

Mixing Default and Non-Default Parameters

Given the following code:

def numbers[one, two=2, three, four=4]:
    n = str[one] + str[two] + str[three] + str[four]
    return n

print[numbers[1, three=3]]

what do you expect will be printed? What is actually printed? What rule do you think Python is following?

  1. 1234
  2. one2three4
  3. 1239
  4. SyntaxError

Given that, what does the following piece of code display when run?

def func[a, b=3, c=6]:
    print['a: ', a, 'b: ', b, 'c:', c]

func[-1, 2]

  1. a: b: 3 c: 6
  2. a: -1 b: 3 c: 6
  3. a: -1 b: 2 c: 6
  4. a: b: -1 c: 2

Solution

Attempting to define the numbers function results in 4. SyntaxError. The defined parameters two and four are given default values. Because one and three are not given default values, they are required to be included as arguments when the function is called and must be placed before any parameters that have default values in the function definition.

The given call to func displays a: -1 b: 2 c: 6. -1 is assigned to the first parameter a, 2 is assigned to the next parameter b, and c is not passed a value, so it uses its default value 6.

Readable Code

Revise a function you wrote for one of the previous exercises to try to make the code more readable. Then, collaborate with one of your neighbors to critique each other’s functions and discuss how your function implementations could be further improved to make them more readable.

Key Points

  • Define a function using def function_name[parameter].

  • The body of a function must be indented.

  • Call a function using function_name[value].

  • Numbers are stored as integers or floating-point numbers.

  • Variables defined within a function can only be seen and used within the body of the function.

  • Variables created outside of any function are called global variables.

  • Within a function, we can access global variables.

  • Variables created within a function override global variables if their names match.

  • Use help[thing] to view help for something.

  • Put docstrings in functions to provide help for that function.

  • Specify default values for parameters when defining a function using name=value in the parameter list.

  • Parameters can be passed by matching based on name, by position, or by omitting them [in which case the default value is used].

  • Put code whose parameters change frequently in a function, then call it with different parameter values to customize its behavior.

Errors and Exceptions

Overview

Teaching: 30 min
Exercises: 0 min

Questions

  • How does Python report errors?

  • How can I handle errors in Python programs?

Objectives

  • To be able to read a traceback, and determine where the error took place and what type it is.

  • To be able to describe the types of situations in which syntax errors, indentation errors, name errors, index errors, and missing file errors occur.

Every programmer encounters errors, both those who are just beginning, and those who have been programming for years. Encountering errors and exceptions can be very frustrating at times, and can make coding feel like a hopeless endeavour. However, understanding what the different types of errors are and when you are likely to encounter them can help a lot. Once you know why you get certain types of errors, they become much easier to fix.

Errors in Python have a very specific form, called a traceback. Let’s examine one:

# This code has an intentional error. You can type it directly or
# use it for reference to understand the error message below.
def favorite_ice_cream[]:
    ice_creams = [
        'chocolate',
        'vanilla',
        'strawberry'
    ]
    print[ice_creams[3]]

favorite_ice_cream[]

---------------------------------------------------------------------------
IndexError                                Traceback [most recent call last]
 in []
      9     print[ice_creams[3]]
      10
----> 11 favorite_ice_cream[]

 in favorite_ice_cream[]
      7         'strawberry'
      8     ]
----> 9     print[ice_creams[3]]
      10
      11 favorite_ice_cream[]

IndexError: list index out of range

This particular traceback has two levels. You can determine the number of levels by looking for the number of arrows on the left hand side. In this case:

  1. The first shows code from the cell above, with an arrow pointing to Line 11 [which is favorite_ice_cream[]].

  2. The second shows some code in the function favorite_ice_cream, with an arrow pointing to Line 9 [which is print[ice_creams[3]]].

The last level is the actual place where the error occurred. The other level[s] show what function the program executed to get to the next level down. So, in this case, the program first performed a function call to the function favorite_ice_cream. Inside this function, the program encountered an error on Line 6, when it tried to run the code print[ice_creams[3]].

Long Tracebacks

Sometimes, you might see a traceback that is very long – sometimes they might even be 20 levels deep! This can make it seem like something horrible happened, but the length of the error message does not reflect severity, rather, it indicates that your program called many functions before it encountered the error. Most of the time, the actual place where the error occurred is at the bottom-most level, so you can skip down the traceback to the bottom.

So what error did the program actually encounter? In the last line of the traceback, Python helpfully tells us the category or type of error [in this case, it is an IndexError] and a more detailed error message [in this case, it says “list index out of range”].

If you encounter an error and don’t know what it means, it is still important to read the traceback closely. That way, if you fix the error, but encounter a new one, you can tell that the error changed. Additionally, sometimes knowing where the error occurred is enough to fix it, even if you don’t entirely understand the message.

If you do encounter an error you don’t recognize, try looking at the official documentation on errors. However, note that you may not always be able to find the error there, as it is possible to create custom errors. In that case, hopefully the custom error message is informative enough to help you figure out what went wrong.

Syntax Errors

When you forget a colon at the end of a line, accidentally add one space too many when indenting under an if statement, or forget a parenthesis, you will encounter a syntax error. This means that Python couldn’t figure out how to read your program. This is similar to forgetting punctuation in English: for example, this text is difficult to read there is no punctuation there is also no capitalization why is this hard because you have to figure out where each sentence ends you also have to figure out where each sentence begins to some extent it might be ambiguous if there should be a sentence break or not

People can typically figure out what is meant by text with no punctuation, but people are much smarter than computers. If Python doesn’t know how to read the program, it will give up and inform you with an error. For example:

def some_function[]
    msg = 'hello, world!'
    print[msg]
     return msg

  File "", line 1
    def some_function[]
                       ^
SyntaxError: invalid syntax

Here, Python tells us that there is a SyntaxError on line 1, and even puts a little arrow in the place where there is an issue. In this case the problem is that the function definition is missing a colon at the end.

Actually, the function above has two issues with syntax. If we fix the problem with the colon, we see that there is also an IndentationError, which means that the lines in the function definition do not all have the same indentation:

def some_function[]:
    msg = 'hello, world!'
    print[msg]
     return msg

  File "", line 4
    return msg
    ^
IndentationError: unexpected indent

Both SyntaxError and IndentationError indicate a problem with the syntax of your program, but an IndentationError is more specific: it always means that there is a problem with how your code is indented.

Tabs and Spaces

Some indentation errors are harder to spot than others. In particular, mixing spaces and tabs can be difficult to spot because they are both whitespace. In the example below, the first two lines in the body of the function some_function are indented with tabs, while the third line — with spaces. If you’re working in a Jupyter notebook, be sure to copy and paste this example rather than trying to type it in manually because Jupyter automatically replaces tabs with spaces.

def some_function[]:
	msg = 'hello, world!'
	print[msg]
        return msg

Visually it is impossible to spot the error. Fortunately, Python does not allow you to mix tabs and spaces.

  File "", line 4
    return msg
              ^
TabError: inconsistent use of tabs and spaces in indentation

Variable Name Errors

Another very common type of error is called a NameError, and occurs when you try to use a variable that does not exist. For example:

---------------------------------------------------------------------------
NameError                                 Traceback [most recent call last]
 in []
----> 1 print[a]

NameError: name 'a' is not defined

Variable name errors come with some of the most informative error messages, which are usually of the form “name ‘the_variable_name’ is not defined”.

Why does this error message occur? That’s a harder question to answer, because it depends on what your code is supposed to do. However, there are a few very common reasons why you might have an undefined variable. The first is that you meant to use a string, but forgot to put quotes around it:

---------------------------------------------------------------------------
NameError                                 Traceback [most recent call last]
 in []
----> 1 print[hello]

NameError: name 'hello' is not defined

The second reason is that you might be trying to use a variable that does not yet exist. In the following example, count should have been defined [e.g., with count = 0] before the for loop:

for number in range[10]:
    count = count + number
print['The count is:', count]

---------------------------------------------------------------------------
NameError                                 Traceback [most recent call last]
 in []
      1 for number in range[10]:
----> 2     count = count + number
      3 print['The count is:', count]

NameError: name 'count' is not defined

Finally, the third possibility is that you made a typo when you were writing your code. Let’s say we fixed the error above by adding the line Count = 0 before the for loop. Frustratingly, this actually does not fix the error. Remember that variables are case-sensitive, so the variable count is different from Count. We still get the same error, because we still have not defined count:

Count = 0
for number in range[10]:
    count = count + number
print['The count is:', count]

---------------------------------------------------------------------------
NameError                                 Traceback [most recent call last]
 in []
      1 Count = 0
      2 for number in range[10]:
----> 3     count = count + number
      4 print['The count is:', count]

NameError: name 'count' is not defined

Index Errors

Next up are errors having to do with containers [like lists and strings] and the items within them. If you try to access an item in a list or a string that does not exist, then you will get an error. This makes sense: if you asked someone what day they would like to get coffee, and they answered “caturday”, you might be a bit annoyed. Python gets similarly annoyed if you try to ask it for an item that doesn’t exist:

letters = ['a', 'b', 'c']
print['Letter #1 is', letters[0]]
print['Letter #2 is', letters[1]]
print['Letter #3 is', letters[2]]
print['Letter #4 is', letters[3]]

Letter #1 is a
Letter #2 is b
Letter #3 is c

---------------------------------------------------------------------------
IndexError                                Traceback [most recent call last]
 in []
      3 print['Letter #2 is', letters[1]]
      4 print['Letter #3 is', letters[2]]
----> 5 print['Letter #4 is', letters[3]]

IndexError: list index out of range

Here, Python is telling us that there is an IndexError in our code, meaning we tried to access a list index that did not exist.

File Errors

The last type of error we’ll cover today are those associated with reading and writing files: FileNotFoundError. If you try to read a file that does not exist, you will receive a FileNotFoundError telling you so. If you attempt to write to a file that was opened read-only, Python 3 returns an UnsupportedOperationError. More generally, problems with input and output manifest as IOErrors or OSErrors, depending on the version of Python you use.

file_handle = open['myfile.txt', 'r']

---------------------------------------------------------------------------
FileNotFoundError                         Traceback [most recent call last]
 in []
----> 1 file_handle = open['myfile.txt', 'r']

FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'

One reason for receiving this error is that you specified an incorrect path to the file. For example, if I am currently in a folder called myproject, and I have a file in myproject/writing/myfile.txt, but I try to open myfile.txt, this will fail. The correct path would be writing/myfile.txt. It is also possible that the file name or its path contains a typo.

A related issue can occur if you use the “read” flag instead of the “write” flag. Python will not give you an error if you try to open a file for writing when the file does not exist. However, if you meant to open a file for reading, but accidentally opened it for writing, and then try to read from it, you will get an UnsupportedOperation error telling you that the file was not opened for reading:

file_handle = open['myfile.txt', 'w']
file_handle.read[]

---------------------------------------------------------------------------
UnsupportedOperation                      Traceback [most recent call last]
 in []
      1 file_handle = open['myfile.txt', 'w']
----> 2 file_handle.read[]

UnsupportedOperation: not readable

These are the most common errors with files, though many others exist. If you get an error that you’ve never seen before, searching the Internet for that error type often reveals common reasons why you might get that error.

Reading Error Messages

Read the Python code and the resulting traceback below, and answer the following questions:

  1. How many levels does the traceback have?
  2. What is the function name where the error occurred?
  3. On which line number in this function did the error occur?
  4. What is the type of error?
  5. What is the error message?

# This code has an intentional error. Do not type it directly;
# use it for reference to understand the error message below.
def print_message[day]:
    messages = {
        'monday': 'Hello, world!',
        'tuesday': 'Today is Tuesday!',
        'wednesday': 'It is the middle of the week.',
        'thursday': 'Today is Donnerstag in German!',
        'friday': 'Last day of the week!',
        'saturday': 'Hooray for the weekend!',
        'sunday': 'Aw, the weekend is almost over.'
    }
    print[messages[day]]

def print_friday_message[]:
    print_message['Friday']

print_friday_message[]

---------------------------------------------------------------------------
KeyError                                  Traceback [most recent call last]
 in []
     14     print_message['Friday']
     15
---> 16 print_friday_message[]

 in print_friday_message[]
     12
     13 def print_friday_message[]:
---> 14     print_message['Friday']
     15
     16 print_friday_message[]

 in print_message[day]
      9         'sunday': 'Aw, the weekend is almost over.'
     10     }
---> 11     print[messages[day]]
     12
     13 def print_friday_message[]:

KeyError: 'Friday'

Solution

  1. 3 levels
  2. print_message
  3. 11
  4. KeyError
  5. There isn’t really a message; you’re supposed to infer that Friday is not a key in messages.

Identifying Syntax Errors

  1. Read the code below, and [without running it] try to identify what the errors are.
  2. Run the code, and read the error message. Is it a SyntaxError or an IndentationError?
  3. Fix the error.
  4. Repeat steps 2 and 3, until you have fixed all the errors.

def another_function
  print['Syntax errors are annoying.']
   print['But at least Python tells us about them!']
  print['So they are usually not too hard to fix.']

Solution

SyntaxError for missing []: at end of first line, IndentationError for mismatch between second and third lines. A fixed version is:

def another_function[]:
    print['Syntax errors are annoying.']
    print['But at least Python tells us about them!']
    print['So they are usually not too hard to fix.']

Identifying Variable Name Errors

  1. Read the code below, and [without running it] try to identify what the errors are.
  2. Run the code, and read the error message. What type of NameError do you think this is? In other words, is it a string with no quotes, a misspelled variable, or a variable that should have been defined but was not?
  3. Fix the error.
  4. Repeat steps 2 and 3, until you have fixed all the errors.

for number in range[10]:
    # use a if the number is a multiple of 3, otherwise use b
    if [Number % 3] == 0:
        message = message + a
    else:
        message = message + 'b'
print[message]

Solution

3 NameErrors for number being misspelled, for message not defined, and for a not being in quotes.

Fixed version:

message = ''
for number in range[10]:
    # use a if the number is a multiple of 3, otherwise use b
    if [number % 3] == 0:
        message = message + 'a'
    else:
        message = message + 'b'
print[message]

Identifying Index Errors

  1. Read the code below, and [without running it] try to identify what the errors are.
  2. Run the code, and read the error message. What type of error is it?
  3. Fix the error.

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print['My favorite season is ', seasons[4]]

Solution

IndexError; the last entry is seasons[3], so seasons[4] doesn’t make sense. A fixed version is:

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print['My favorite season is ', seasons[-1]]

Key Points

  • Tracebacks can look intimidating, but they give us a lot of useful information about what went wrong in our program, including where the error occurred and what type of error it was.

  • An error having to do with the ‘grammar’ or syntax of the program is called a SyntaxError. If the issue has to do with how the code is indented, then it will be called an IndentationError.

  • A NameError will occur when trying to use a variable that does not exist. Possible causes are that a variable definition is missing, a variable reference differs from its definition in spelling or capitalization, or the code contains a string that is missing quotes around it.

  • Containers like lists and strings will generate errors if you try to access items in them that do not exist. This type of error is called an IndexError.

  • Trying to read a file that does not exist will give you an FileNotFoundError. Trying to read a file that is open for writing, or writing to a file that is open for reading, will give you an IOError.

Defensive Programming

Overview

Teaching: 30 min
Exercises: 10 min

Questions

  • How can I make my programs more reliable?

Objectives

  • Explain what an assertion is.

  • Add assertions that check the program’s state is correct.

  • Correctly add precondition and postcondition assertions to functions.

  • Explain what test-driven development is, and use it when creating new functions.

  • Explain why variables should be initialized using actual data values rather than arbitrary constants.

Our previous lessons have introduced the basic tools of programming: variables and lists, file I/O, loops, conditionals, and functions. What they haven’t done is show us how to tell whether a program is getting the right answer, and how to tell if it’s still getting the right answer as we make changes to it.

To achieve that, we need to:

  • Write programs that check their own operation.
  • Write and run tests for widely-used functions.
  • Make sure we know what “correct” actually means.

The good news is, doing these things will speed up our programming, not slow it down. As in real carpentry — the kind done with lumber — the time saved by measuring carefully before cutting a piece of wood is much greater than the time that measuring takes.

Assertions

The first step toward getting the right answers from our programs is to assume that mistakes will happen and to guard against them. This is called defensive programming, and the most common way to do it is to add assertions to our code so that it checks itself as it runs. An assertion is simply a statement that something must be true at a certain point in a program. When Python sees one, it evaluates the assertion’s condition. If it’s true, Python does nothing, but if it’s false, Python halts the program immediately and prints the error message if one is provided. For example, this piece of code halts as soon as the loop encounters a value that isn’t positive:

numbers = [1.5, 2.3, 0.7, -0.001, 4.4]
total = 0.0
for num in numbers:
    assert num > 0.0, 'Data should only contain positive values'
    total += num
print['total is:', total]

---------------------------------------------------------------------------
AssertionError                            Traceback [most recent call last]
 in []
      2 total = 0.0
      3 for num in numbers:
----> 4     assert num > 0.0, 'Data should only contain positive values'
      5     total += num
      6 print['total is:', total]

AssertionError: Data should only contain positive values

Programs like the Firefox browser are full of assertions: 10-20% of the code they contain are there to check that the other 80–90% are working correctly. Broadly speaking, assertions fall into three categories:

  • A precondition is something that must be true at the start of a function in order for it to work correctly.

  • A postcondition is something that the function guarantees is true when it finishes.

  • An invariant is something that is always true at a particular point inside a piece of code.

For example, suppose we are representing rectangles using a tuple of four coordinates [x0, y0, x1, y1], representing the lower left and upper right corners of the rectangle. In order to do some calculations, we need to normalize the rectangle so that the lower left corner is at the origin and the longest side is 1.0 units long. This function does that, but checks that its input is correctly formatted and that its result makes sense:

def normalize_rectangle[rect]:
    """Normalizes a rectangle so that it is at the origin and 1.0 units long on its longest axis.
    Input should be of the format [x0, y0, x1, y1].
    [x0, y0] and [x1, y1] define the lower left and upper right corners
    of the rectangle, respectively."""
    assert len[rect] == 4, 'Rectangles must contain 4 coordinates'
    x0, y0, x1, y1 = rect
    assert x0 

Chủ Đề