Oklahoma School of Science and Math

Practicing Math by Playing with Python

Hille Institute, 2007 edition

Dr. J Adrian Zimmer

A self contained version of Python that automatically loads the workspace described here is available.. You can load it on any Windows disc drive, including a flash drive.


Installing the Software

  1. Insert the CDROM. When it has settled down, open (by double clicking the left button) “My Computer”. You should see something like this

  2. Copy and paste the K12Python folder to your local C: drive. You have the right place when you see “Local Drive (C:)”.
    • Find the DVD/CD player and double click on it.
    • Find K12Python and right click on it. From the menu that pops up choose "copy".
    • Back out of the DVD/CD folder to what you saw above.
    • Right click on “Local Drive (C:)” and choose "paste" from the menu that pops up.
  3. Open the “Local Drive (C:)” folder (by double left clicking on it). You should see the K12Python folder again. (This time you are seeing a copy on your C: drive.) Open the K12Python folder as well.
  4. Look for the file named python (not python24 or pythonw; however python.exe is ok). Copy and paste that icon to your desktop (with right clicks the way you did before). You will be asked if you want to create a shortcut answer yes.
  5. You can now run K12Python by clicking on the icon on your desktop. When you do, you should see the following



Running the Software

  1. The normal Python prompt is >>>. When you see this, the Python interpreter is waiting for your input. You can Two such tools we will look at are called rational_numbers, for working with fractions, and graphing for drawing graphs.
Of course, there are lots of other things that can be done with Python. Reformatting text and creating dynamic web pages are two of the most popular. There are whole books written on each of these topics as well as on object-oriented programming in Python. All of that goes beyond what we can do in half a day. A very new book that combines Python with high school mathematics may interest you. It is "Mathematics for the Digital Age and Programming in Python" by Maria and Gary Litvin. Get it from the publisher at http://skylit.com. The Litvin's agree with me that Python offers an opportunity to make mathematical abstractions seem more concrete and they included some of my ideas in their book.


Arithmetic Expressions

Arithmetic expressions are related to the grade six curriculum. Here are some things you can do with them.

  1. enter “2+2” (always without the quotes unless instructed otherwise). The screen will look like this
    >>> 2+2 
    You entered the “2+2”. Python responded with “4” and told you it was ready for more input.
  2. What you must remember when working with Python is that your entire calculation must be entered on one line and that line cannot begin with any extra blanks.

    If you do not follow these rules, you will get a syntax error.

  3. To see what a syntax error looks like enter
    >>> 2+2%
      File "<stdin>", line 1
    SyntaxError: invalid syntax
    There is no problem with making syntax errors. When you make one, simply try again.
  4. Here is what you will see if you put a space before the “2+2”
    >>>    2+2
      File "<stdin>", line 1
    SyntaxError: invalid syntax
  5. Spaces to separate the things you put on a line are allowed. For example,
    >>> 2  +  2
  6. Try calculating each of the following:
    Keep playing with these things until you can explain the meaning of * and **.
Have you seen some anomalies with real numbers? These anomalies are a bit difficult to explain and you may want to stay with integers when in grade 6.


Hardware Quirks and the Way Division Works

  1. Because real numbers, such as 1/3 or 0.333333..., often involve infinite expansions and because computers use binary numbers which have different decimal expansions than we are used to, you will find that arithmetic with real numbers provide some surprising results. For example, try 1/5. The weird result you get is close to the answer you expect but it is a bit off because 1/5 is an infinite decimal in the binary number system.

    So, never expect exact answers when working with real numbers.

  2. Another hardware quirk is that computers have different circuitry for real number arithmetic than they have for integer arithmetic. Compare what you get for 11.0/3.0 with 11/3. In the latter case, the computer is telling you the whole number of 3's that can be in 11.
  3. Try some more divisions.
  4. Of course, one reason we have software is so we won't have to put up with all the hardware quirks. To make Python divide in a more reasonable way do this
    >>> from __future__ import division
    Now try other divisions with integers and with real numbers.
  5. The ability to ask: “What is the whole number of threes that go into eleven?” is still there but now you have to write // instead of /, as in
    >>> 11//3
  6. You might want to know what the remainder is when you divide 3 into 11. Try 11%3.


Parentheses and Order of Operands

These are also sixth grade topics.

  1. Try:
    >>> x = 5+2
    >>> y = 3-4
    >>> x-y
    >>> (5+2)-(3-4)
    Why do the latter two Python calculations produce the same answer? Would they be the same if the parentheses were removed?
  2. Assign other values to x, y, and z and experiment calculating things like x/y+z with different operators and parentheses. Are the results as you expect?

    What you are doing here is making up examples that illustrate the need for parentheses and why the order of the operands is often important. This leads to a nice introduction of the commutative property because we have seen that subtraction is not commutative but addition is.

  3. Not only the order of the operands but also combination of operators makes a difference. Some operators like *, /, //, and / take precedence over others like + and -. Which of the following are equal?



It takes some time to get used to the idea of a variable and grade 6 isn't too early to begin.

  1. Try this
    >>> x = 2
    You have just told Python that, for the time being when you say “x” you mean “2”.
  2. Try some arithmetic expressions with x: x+3, x-3, 3**x, and so forth.
  3. Now try this
    >>>y = x
    >>> x = 3
    What do you expect x and y to represent now? Remember y is given the same value as x before the value of x is changed.
  4. You can always find the value of a variable this way
    >>> x
  5. Try some arithmetic expressions of your own after giving values to x and y.

This is the one place where you must really watch out if teaching Python and mathematics together. In mathematics a variable is assigned a value for one problem and it doesn't change until you start a new problem. In computer science a variable can change its value wheresoever you want it to. Many of us believe that this fact makes computer programming harder than mathematics. When debugging programs, lots of time can be wasted finding out why some variable acquired a crazy value!


Kinds of Numbers

Off the shelf, Python can deal with two kinds of numbers, integers and real numbers. Integers are called ints and real numbers are called floats. Python recognizes a number to be an int if there is no decimal point and a float if there is a decimal point. The word “float” has historical origins and is useful today because it emphasizes that the results you get with floats are not exactly the same as the results you get with real numbers.

Python has functions for converting ints to floats and vice versa.

  1. What is the effect of float(22)? Can you assign something to a so that you will get the same effect with float(a)?
  2. Experiment with int(x) where x is a real number.
  3. If x is a variable representing a real number, how would you round it to an integer using int?

Extra: You won't have time for this today.


Some exercises

Still at the sixth grade level here.

  1. Convert 158 minutes to hours and minutes.
  2. Convert 67 hours 21 minutes to minutes.
  3. Convert 157 inches to feet and inches.
  4. Convert 4 feet 5 inches to inches.


Importing a Tool for Fractions

  1. To use fractions, do this
    >>> import rational_numbers
     rational, numerator, denominator.
    For more information use help(rational), etc.
  2. Fractions are called rationals. Consider this
    >>> f1
    rational(1, 2)
    >>> numerator(f1)
    >>> denominator(f1)
    Make your own fraction, assign it to the variable f2 and check its numerator and denominator
  3. Add f1 and f2. If f2 is rational(2,3) you will get rational(7,6).
  4. Try arithmetic with other fractions.
  5. There is no separate data type for a mixed number but you can force any rational to be converted to a real number.
    >>> float(rational(11,6))
    Try some of your own examples.

Extra: You won't have time for this today.

As an example of using this to teach mathematical properties, you could make examples of the distributive property three ways: with integers, with real numbers, and with fractions.

However, do remember when you do x*(u+v) and (x*u)+(x*v) for real numbers that the answers you get will not necessarily be exactly the same. Why?



Grade seven seems to be a good place to introduce the concept of function which we can think of as a process for making a new number out of an old one. To define (or explain) a function you have to The reason you name the function is so you can refer to it later. The reason you name the starting value is because you have to be able to refer to it when you are explaining the process. Here's an example:

>>> edit()

Python provides no new prompt until a function has been defined. Instead, this window pops up:

In this window we define the function. First, enter this line

def f(x):

This will tell Python that we are not asking to have an expression evaluated. Rather we are making a definition. We are defining a function named “f”. When we get around to explaining the function's process, we will use the variable x to represent the starting value.

To keep things simple, suppose the process of creating another number is merely to add one to the starting value. Then our second line looks like this:

   return x + 1

which tells Python that the new number is going to be x+1. Python already knows that x is the name we use for the starting value.

The starting value is usually called the function's argument.

Here is what our complete definition looks like when entered in the edit window

Before we can use our new function we must check it by clicking on “check”. If it checks out OK, we click on “load”. If not, we edit it and try again. Once f has been defined we can use it in Python expressions like this

>>> f(3)


>>> 2 * f(-1)



It is Python's job to take the number in parentheses, assign it to the variable x, then evaluate the return expression, then return the value obtained. What “return” means is for the first calculation, is to continue calculating as if we had typed 4 instead of f(3) and, for the second calculation, to continue calculating as if we had typed 0 instead of f(-1).

Here is another way to look at function definition. Suppose we wanted to convert a fahrenheit value to centigrade. A somewhat long-winded way of doing this is:

>>> fahr = 18

>>> centigrade = 5*(fahr-32.0)/9

>>> centigrade


Wouldn't it be nicer to just write the following?

>>> centigrade(18)


>>> centigrade(-40)


Isn't the second result curious? I learned this fact, while teaching at the University of Calgary in Alberta. It happened to be -40 that day.

The starting values 18 and -40 are the arguments.

Here is a definition for such a centigrade function:

def centigrade(fahr):

    return 5*(fahr-32.0)/9

You are about ready to try this for yourself. Of course, you will make some mistakes from time to time. There are two kinds of mistakes To fix a logic error you need to re-edit the function. To re-edit a function named f do this

>>> edit(f)

For these exercises, use the fact that a kilometer is six tenths of a mile.

  1. Write and test a function named kilometer that converts miles to kilometers.
  2. Write and test a function named mile that converts kilometers to miles.
  3. Test mile(kilometer(60)) and kilometer(mile(100).


Drawing Graphs

To draw graphs in K12Python you must do this first:

>>> import graphing


 a Graph class; enter help(Graph) for more info

  1. Graph your kilometer with Graph(kilometer).
  2. Define a function g which returns 3 times the cube of its argument. Graph it. The graph looks real bad doesn't it? You need to change the scale. Try this
    You should see something like this graph.

You can also adjust the yaxis and the height. Use yfactor= and height=, respectively.


Restarting K12Python; Saving, Reloading, and Changing Folders

Now that you have some functions written, you may want to save them for another day. You can do this as you shut K12Python down.

>>> quit()

Save this workspace? (y, n, or ?) y

saved to workspace

This does not work if you shut down K12Python by simply closing the window. The next time you start K12Python, you will be asked if you want to reload that workspace. If you answer by entering “y”, all the functions and variables from your saved workspace will be reloaded. Why don't you try quiting, restarting, and reloading?

Extra: You won't have time for this today.

If you want to be able to save more than one workspace you must understand how the folders and files work in your computer. If you do, then know that workspaces are saved in a file named saved_workspace in the current folder. If you want to save different workspaces, then you must save them in different current folders. To change the current folder use changeFolder() which will pop up a window you can browse for the folder you want.

You can save or reload a workspace at anytime. Be sure you are in the correct current folder for that workspace and then use save() to save your current workspace or load() to load the workspace of the current folder into K12Python. Whenever you load a workspace, you are asked if you want to clear out K12Python before the loading takes place.

If you have a function or variable, say its name is k, that you no longer want, then do this

>>> del k


The variable will be removed from K12Python but not from any workspace where it has been saved.

K12Python also has functions for reading and writing text files which will work with files in the current folder. If you write a file with Notepad, you can read it with readString. If you write a file with writeString, you can read it with Notepad. Of course, you will want to learn more about how standard Python handles text before you try this. Text in Python, and most programming languages, is called a “string”.



For the eighth grade you will want to talk about averages and medians. To do that you need to talk about lists of numbers. In Python, lists of numbers are as easy to work with as numbers. Some examples,

>>> [1,2,3]

[1, 2, 3]

>>> [9,8,7]

[1, 3, 2]

>>> [1,2,3] + [9,8,7]

[1, 2, 3, 1, 3, 2]

>>> sorted( [4,2,8,10,-1,0] )

[-1, 0, 2, 4, 8, 10]

>>> x = [1,2,3]

>>> y = [9,8,7]

>>> x + y

[1, 2, 3, 9, 8, 7]

>>> sorted( x + y )

[1, 2, 3, 7, 8, 9]

  1. Create a couple lists of your own and assign them to variables x and y
  2. Try to apply the function sum to your lists. What does it do?
  3. Try to apply the function min to your lists. What does it do?
  4. Try to apply the function max to your lists. What does it do?
  5. Try to apply the function len to your lists. What does it do?
  6. Write a function of your own. Name it average. Your function should start with a list and return a float. The returned float should be the average of the values in the list. You will, of course, be using both the sum and the len functions to accomplish this.


Indexing Lists

It is possible to play with the individual numbers in a list. Consider this

>>> t = [1,2,3]

>>> t

[1, 2, 3]

>>> t[0]


>>> t[1]


>>> t[2]


The numbers 0,1, and 2 are list indexes. The numbers 1,2,3 are list values. We always start counting list indexes at 0 and go up by one each time we move to the right. List values on the, other hand can be anything.

>>> t = [1,1,1]

>>> len(t)


>>> sum(t)


>>> len(t)


>>> u = [5,3,[1,1]]

>>> u[2]


>>> len(u)


>>> sum(u)

Traceback (most recent call last):

  File "", line 1, in ?

TypeError: unsupported operand type(s) for +: 'int' and 'list'


This last use of the sum function didn't work because the list u does not consist solely of numbers. We can make a list of lists, but then we cannot add all the numbers! We can, however, change individual values in a list. Consider this

>>> u[2] = 4

>>> u

[5, 3, 4]

  1. Find the median of [8,2,9,3,6]. (Sort it and take the middle value.)
  2. The range of a list of numbers might be defined as the difference between the highest and lowest numbers in the list. Write and test a function range which returns the range of its list argument.
  3. If lst is a list with an odd number of values, what is lst[ len(lst)//2 ]? (Hint: “It is the index of that value which …” .) Test your answer with some experiments.
  4. If lst is a list with an even number of values, what is lst[ len(lst)//2 ]? Test your answer with some experiments.
One definition of median of a list of numbers says that the median the middle of value of the same list, sorted. If the list has an even number of values and there are two middle values. Here it is convenient to take the larger (rightmost) one as the median. With this definition, the formula you have been testing can be be used to write a function which will return the median of a list of numbers. Here it is

def median(lst):

    middle = len(lst)//2

    sortedlst = sorted( lst )

    return sortedlst[middle]

Notice that this function definition involves more than just a return statement. It is always possible to put extra statements before the return statement. We do this when we want to create variables that will make the expression in the return statement easier to write.

One important caveat: All the statements in your function definition must be indented exactly the same amount!


About K12Python

K12Python was written at the Oklahoma School of Science and Mathematics by me, Dr. J Adrian Zimmer. Its purpose is to provide a version of Python that is even more encouraging of student experimentation than is standard Python. The current version is 0.1.1.

When you start K12Python, all the differences between it and standard Python are listed as a startup message. When you import either of K12Python's modules, rational_numbers and graphing, the things they add to Python are again listed as the module imports. (The rational_numbers module, by the way, was not written by me. All I did was repackage a version that can be found at the Python web site.)

K12Python is available as open source software from my web site. This web site is being redesigned during the summer of 2007 so I am not exactly sure where to tell you to look. Try





in that order.

Extra: you won't have time for this today.

My way of learning mathematics has always been to find a problem I find a bit tricky and solve it. Here are some suggestions which I think might  be right for you. Yes, they are computer problems rather than math problems, but solving them requires a bit of what is known as “mathematical maturity”.

  1. Can you rewrite the median function so that there is no need for the variables middle and sortedlst?
  2. Suppose
    >>> x = 2
    >>> y = 3
    How would you swap the values assigned to x and y if you didn't know they were 2 and 3? (Hint: you will need to use a third variable.)
  3. Suppose you didn't want to write float(3) but wanted to write real(3) instead. Find two ways of enabling this.

    def median(lst):
       return sorted( lst )[ len(lst)//2 ]
    >>> z = x
    >>> x = y
    >>> y = z
  3. The most obvious way would be to enter edit and then make this definition
    def real(x):
       return float(x)
    Another way relies on the fact that variables in Python need not refer to only numbers and lists of numbers, they can refer to functions. So you can name a variable real and assign the function we know as float to it. As in, real = float.