COMP 200 Elements of Computer Science &
COMP 130 Elements of Algorithms and Computation
Spring 2012

Introductory Python “Finger Exercises”

These exercises will introduce some of the basics of using Python. You do not need to turn in any of the following work.

Using our software: Hello, World!

We are now ready to write our first Python program, and thus to see how the editor and Python work together. There are three sets of instructions here:

Calculating with Numbers

You can use the IDLE shell or the ipython interpreter for this section. Both are essentially Python “calculators” — you enter a formula or, more generally, any Python piece of code, and it shows you the result. This is very useful for experimenting with little pieces of code.

At the prompt, type a simple mathematical expression:

Try some more math expressions. Try mixing various arithmetic operations such as +, -, / (divide) and * (multiply). Throw in some round parentheses, ( and ), too! (You can try square parentheses if you want — what do you think is going on with the funky results? We'll get to that soon enough!)

Try the following experiments. First, type in the following division calculations:

Did you get what you expected? Next, try these expressions. What is the difference between the first set and the second? Is Python brain-dead when it comes to math or is it actually calculating the correct answer both times? Finally, what happens if you mix integers with floating point values in a calculation? Try it! E.g.,

Let's try a more meaningful calculation: converting a temperature value from Fahrenheit to Celsius. Suppose the temperature is 86° Fahrenheit. What's the corresponding Celsius temperature? If you don't know or remember the conversion formula, consult an expert: Google it! Don't peek at the provided solution until you've tried it yourself.

Try it for several different Fahrenheit temperatures. The boiling point of water is 212° Fahrenheit or 100° Celsius. The freezing point of water is 32° Fahrenheit or 0° Celsius. The “normal” human body temperature is 98.6° Fahrenheit, or 37° Celsius. Again, try it yourself before looking at the provided solutions.

Now convert the above sample temperatures from Celsius to Fahrenheit. Again, you may wish to consult an expert for the formula.

Can you find the temperature that is the same in either Fahrenheit or Celsius?

Strings

So we've proven that Python can be used as a glorified calculator. What about stuff that aren't numbers? A string is an data entity that consists of multiple characters enclosed in either double or single quotes (either, just be consistent). Type a sentence enclosed in quotes:

Instead of typing the math expressions you did before, try typing them enclosed with quotes, e.g.,

Why don't you get 5? Because these are just some digits and symbols that we've put together, not really a mathematical expression.

Now try this:

Combining two strings into one is called concatenation.

Can you concatenate more than one string at once? Try it!

Can you concatenate a string with a number? Try it. Can you explain the results?

Additional optional readings about Python strings

Printing

Try typing the following expressions.

It looks as if print isn't doing anything at all, but in fact, it is doing exactly what the interactive Python environment is already doing, naming “printing” the calculation result to the screen. There's one big difference however: print does so under our programmatic control. That means that we can control when and what gets shown on the screen. This will prove very, very handy later on.

Abstracting computations with variables

Let's return to our temperature conversion exercise. While it wasn't too hard to convert different Fahrenheit values to their Celsius counterparts, what if the formula was much more complicated, you wanted to use a thousand variations of it, or the time between calculations wasn't just a few seconds but days or months? If you had to close the interactive Python interpreter between calculations, you'd have to retype the formula every time you did a calculation.

Ah, but those warm and fuzzy memories of algebra come flooding back to you. Can't you represent the formula in terms of something more abstract, namely in terms of variables?

The algebraic definition would look something like this:

Let F be the temperature in degrees Fahrenheit. Then, the temperature in degrees Celsius is (F-32)×5/9.

In Python, you could represent this as follows:

We have introduced a variable F with the value of 86. The Celsius temperature calculation uses that value of F. The key thing to note here is that the temperature conversion calculation is now independent of the value of the Fahrenheit temperature. That is, the conversion calculation is an abstraction of the conversion process. We can see this because we can simply redo the setting of the value of F and then re-run exactly the same conversion calculation — just use the up-arrow key to go back to the formula, and press Enter.

One of the ways in which we can talk about this is to say that the conversion calculation is now an invariant because it never changes while the value of the Fahrenheit temperature, F, is a variant because its value can change. Notice the simplicity brought on by the abstraction afforded by the use of variables. Doing another conversion has been reduced to simply changing the value of F.

Abstracting computations with functions

So far, so good. But we what if we want to use the F variable for something else? “F” could be for “Fuel” or “Films” or something else. I suppose we could have named our variable “Fahrenheit_temperature” but that's a lot of typing, and what if we need to deal with more than one temperature simultaneously? Also, scrolling up to find that old formula is a pain. What if we have been working all day and there are thousands of calculations we've been doing and the temperature conversion is just one of many buried in a huge pile of formulas. There's got to be a better way.

Calculating with functions

In our search for a better solution, let us seemingly digress for a moment.

In Python, the exponentiation operator is a double-asterisk. For example, 2 to the power of 3 is written as 2**3. Give it a try!

But there's another way of doing exponentiation. Try typing this:

Here, pow is a function, specifically, a function of two input parameters. It takes two values and returns a value that is equal the power of the first input raised to the second input. The parentheses and comma are used to distinguish the input parameters from each other and from other values in an expression.

The important thing to understand about functions is that calling, i.e., using, a function is equivalent to using the value that the function returns, i.e., computes. Note that we make a distinction between calling or using a function from defining a function, which is to write the code for one, something we will do in a moment. That is, conceptually, wherever we see a function being used in an expression, we can effectively replace that function call with the value that it returns.

Let's do an example to show this very important notion. Let us define 3 variables, then use them:

Is the result what you expect?

Now let's consider what Python is doing to get this result. In order to understand how to write a program, we need to understand the basics of what the computer will do with it.

Note that we were following the standard order of operations you're already used to.

So what does a function do for us? It encapsulates (covers up and hides away) a potentially complicated calculation, enabling us to simply deal with the abstraction of that calculation. I.e., we only need to think about what will be calculated, not how.

This is a tremendously powerful notion. It means that we can take complicated calculations that may involves thousands of lines of complex code and wrap them up neatly in a function that we can pop into wherever we need. This keeps everything else very simply, enabling us to build even bigger, even more complex systems from building blocks of functions. This building technique will be the basis of how most everything in computing is done. The importance of understanding functions and how they work cannot be underestimated.

There are a number of other built-in functions that you should try. The following is a tiny sampling. We'll see more later.

Try mixing up functions, variables, and simple values together in as big and complicated an expression as you can think of!

Creating a function

Now back to business and see how to write our own function.

What we want to do is to define a new function to convert Fahrenheit values to Celsius values. It is important to re-emphasize the difference between using or calling or executing a function and defining or declaring a function. When using a function, we are writing code which refers to an existing function. It causes the function to operate on its inputs (if any) and to return a result. This is what we have been doing in the previous examples like pow(2,3). When defining a function, we write code to tell the computer that a function with a specific name now exists and how it works. This is what we are about to do.

Defining the temperature conversion functions

Let's define a function called convertF2C that will convert a Fahrenheit value to a Celsius value. We start the definition with the special Python keyword def.

The above line of code means we are defining a function called convertF2C that takes one input parameter, which we will called F. In fancy computer geek-speak, this is the function's signature.

We already know the conversion formula, so let's just type it in and then keep pressing Enter until you get back to the main Python prompt.

What we wrote are instructions that tell the computer to do the conversion calculation whenever we call convertF2C with some value, e.g., convertF2C(75). The code says that whatever the input value is, denoted by F, subtract 32 from it and multiply it by 5/9.

It looks good, so try your new function with some values.

Did it do what you thought it would do?

If you accurately typed what was shown above, I guarantee you that the computer did exactly the following: It took the value, say 212, subtracted 32 from it, multiplied it by 5 and then divided it by 9. So what's wrong? Here's the mantra to remember.

“A computer is just a dumb hunk of silicon, plastic, and wires and doesn't know how to do anything, no matter how obvious!”
Yeah, the computer did the conversion calculation, but since we didn't tell the function to return that value to us to use for other things, such as display the result on the screen, it simply threw the calculation results away!

What we need to do is to explicitly tell the function to return the calculation results to us. We'll use the Python keyword return to do this. Let's try retyping the function but this time, we'll put the word return in front of the calculation expression:

def convertF2C(F):
    return (F-32) * 5.0/9.0

And now try your new version to see if it works.

Ahhh, that's better!

Write a few functions on your own before peeking at the provided solutions:

Try any other functions you can imagine. Go crazy!

A final word about local and global variables

Let's try an experiment. Make sure your convertF2C function is defined as above. Run your convertF2C with some value, say 212, to make sure it works. At the Python prompt, create a variable with the same name as the one you used in your function, e.g., F, assigning it a different value than what you just tested your function with. Now try running convertF2C again, with the same value you did before, e.g., convertF2C(212).

convertF2C(212)
F = -42
convertF2C(212)

Try this several times, using different values for F and the function input. Did F's value have any effect on convertF2C's behavior? What's going on?

It turns out that we actually have two different variables called F here:

Additional optional readings about Python