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:
-
2+3
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:
-
4/2
-
4/3
-
4/4
-
4/5
-
4.0/2.0
-
4.0/3.0
-
4.0/4.0
-
4.0/5.0
-
4.0/5
-
4/5.0
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.
-
(86 - 32) * 5.0 / 9.0
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.
-
(212 - 32) * 5.0 / 9.0
-
(32 - 32) * 5.0 / 9.0
-
(98.6 - 32) * 5.0 / 9.0
Now convert the above sample temperatures from Celsius to Fahrenheit. Again, you may wish to consult an expert for the formula.
-
100 * 9.0 / 5.0 + 32
Can you find the temperature that is the same in either Fahrenheit or Celsius?
-
-40 * 9.0 / 5.0 + 32
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:
-
"CS is da bomb!"
Instead of typing the math expressions you did before, try typing them enclosed with quotes, e.g.,
-
"2+3"
Now try this:
-
"Yo ho ho " + "and a bottle of rum!"
Can you concatenate more than one string at once? Try it!
-
"This " + "is" + " fun!"
Can you concatenate a string with a number? Try it. Can you explain the results?
Additional optional readings about Python strings
- Python Tutorial: Strings
- Wikibooks: Python strings
- Khan Academy: Python strings
- Python documentation: Common string operations
Printing
Try typing the following expressions.
-
print 2+3
-
print "Yo ho ho " + "and a bottle of rum!"
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:
-
F=86 (F-32)*5.0/9.0
-
F=212 (F-32)*5.0/9.0
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!
-
2**3
But there's another way of doing exponentiation. Try typing this:
-
pow(2,3)
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:
-
x=3 y=7 z=2 x+pow(y,z)
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.
-
We start with our expression:
-
x+pow(y,z)
-
-
Replace all the variables with their current values.
-
3+pow(7,2)
-
-
Compute
pow
's result.-
3+49
-
-
Compute the addition's result.
-
52
-
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.
-
abs
: the absolute value of a number, e.g.,abs(-42)
-
str
: converts a number into a string, e.g.,str(42) + " is the answer."
-
float
: converts an integer into a floating point number, e.g.,float(5)/9
-
int
: converts an floating point number into an integer, e.g.,int(5.2)
orint(5.8)
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
.
-
def convertF2C(F):
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.
-
def convertF2C(F): (F-32) * 5.0/9.0
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.
-
convertF2C(212)
-
convertF2C(32)
-
convertF2C(98.6)
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.
-
convertF2C(212)
-
convertF2C(32)
-
convertF2C(98.6)
Write a few functions on your own before peeking at the provided solutions:
-
A function to convert Celsius to Fahrenheit
def convertC2F(C): return C * 9.0/5.0 + 32
-
A function that will concatenate
“ and it's Greeeaaaatttt!!” to the end
of any string.
def concatGreat(s): return s + "and it's Greeeaaaatttt!!"
-
A function that will give you the sum of squares of two input values.
def sumSquares(x,y): return x*x + y*y
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:
- A global variable — This is the one defined at the Python prompt. It exists outside of any function, but is accessible to any function if it should so choose. This variable exists for as long as your Python session runs. This means that every global variable should have a unique name.
- A local variable — This is the one that is defined as part of the function definition, such as an input parameter, though it is not necessarily limited to just that. This variable really only exists during the brief time period as the function actually executes. It does not exist outside that particular function at all. We say that it is limited to the scope of that function. That means that multiple functions can have local variables with the same name and not interfere with each other. That means you can write a function without having to worry how you or anyone else wrote some other function. Very handy!