# Operation 1:
print(4 * (2 - 8) + 2)
# Operation 2:
print(4 * 2 - 8 + 2)
-22
2
In this first proper programming lesson we are going to use the Python interpreter to perform simple operations, like numeric calculations that you would normally do on a calculator and slightly more advanced operations on words. The interpreter is what reads your code and converts that into the binary instructions that the computer can understand – think of it as translator between you and the low-level components (operating system, file system, network, display, etc.) of your machine. The interpreter operates in the background and runs when you click the ‘Run’ button in your working envirnment (in future we’ll see how we can use the Python interpreter with scripts of many lines of code).
As we progress through the excercises we’ll encounter a range of new programming concepts. At this stage don’t worry too much about memorizing all of them; it is through repeated use and practice that they will eventually come naturally. Instead, here we want you to try to develop a sense of what is going on and keep the concepts in mind when reading the examples… but the really important thing is to try to apply them while doing the excercises.
Lastly, a few words on the excercises; in every lesson we’ve tried to develop a mix of exercises and examples to show you how Python works. There are four ‘levels’ of exercise:
???
) in order to make it work successfully.We’re not expecting you to master the fourth level at this stage; in fact, some of the examples might be challenging even after a full year of classes. However, we think it’s important to try to show you where we’re trying to go as well as the steps involved in how we get there. It’s like trying to follow directions from someone who only tells you ‘turn left’, ‘turn right’, ‘go straight’ – it’s a lot easier to fill in the gaps and to understand what’s going on if they say “We’re headed to London” first!
You already saw a really simple example of calculating the mean in the first lesson, but let’s recall that you can easily use Python to like a calculator. Run the code already present in the code cells and make sure you understand the output. To do this, just click on the clipboard icon to copy the code and paste it in your working environment (either locally or online)
Do you think the results of these two operations will be identical? If not, why? Decide what you think the answer is before running the code!
Always remember the importance of parentheses in determining ‘precedence’ – which operations get done first.
You might have also psotted that the code above wraps each formula in a print()
command; this allows us to print out the results of both calculations when the code runs. Without the print
we’d only see the results of the last (i.e. second) operation. We’ll come back to this later.
Anyway, even if it’s been a long time since you’ve tried to do any maths, hopefully it’s coming back to you that:
is not the same as:
If you use two asterisks instead of one then you’ll be performing an exponentiation:
That’s the same as:
So 2**4
is how we get 2-to-the-power-of-4 (the same as multiplying 2 together 4 times). Hopefully this all kind of rings a bell even if you’ve not studied any maths in a while.
So 2**4
is 2-to-the-power-of-4, but how do we get the square root (or fourth root) of a number? Right now, with what we’ve taught you so far, the best way is to remember that a square root is the same as an exponent of one-half. The fourth root is an exponent of one-quarter. So…
Notice that even though the answer to the second operation is a whole number we’re getting back a decimal. This is your first introduction to the idea that variables might have types and that integers are different from non-integers. There’s lots more about this to come. But let’s start with…
Many programming languages (Python used to be one of them) treat whole numbers (1
, 8
) differently from floating point numbers (1.0
, 8.000000000001
). In those cases, we get the counterintuitive answer of 0
to the first equation because, when we use whole numbers in our calculations, we got whole numbers back. 1/8
is obviously not 0
, but that’s the nearest whole number to 0.125
! This is what we mean about computers doing exactly what you tell them: sometimes you want 1/8
to equal 0
, other times you’d want 0.125
, and the computer doesn’t know which answer you need unless you are very clear about what you want!
While we’re on the topic of division, how do you get the ‘remainder’ of 9/2 – the bit left over from the division? To get this there is a different symbol called the modulo operator which is a marked by a %
sign. According in fact to the Python Documentation
The % (modulo) operator yields the remainder from the division of the first argument by the second.
Using the modulo operator will thus return the remainder:
Just to make this clear: 2 goes into 9 exactly 4 times and then you have 1 left over. So: (4 * 2) + 1 = 9
.
For division which yields no remainder the operation will return a value of 0.
What do you think will be the result of this operation? Work out your answer before running the code.
Now what do you think this will give you? Again, work out your answer before running the code.
This is a bit trickier since it depends on operator precedence. So parentheses are first: 1) 2*3
and 2) 12 % 5
. Then it’s the exponent ** 2
. Last is the division operation (/
). So the answer is 18.0.
In the code below replace the question marks ???
with the appropriate code to produce a remainder of 6. You may need a calculator to help you. Run the code to check your answer; you can change your answer and run the code multiple times until you get the right answer.
It’s pretty straightforward to work out that the left half of this equation produces 36
. So to get a remainder of 6
we need the right half to evaluate to 10
(36 % 10 == 6
; technically, 30
is another solution so that would allow 4
as an answer too).
The mathematical operations (+
, -
, *
, **
, /
, %
, etc., and the parentheses) are all evaluated (i.e. calculated) according to a set of rules that establish their precedence. This is just a fancy way of saying: which calculations do we do first? There’s a full list here but since that also lists a lot of operators we’ve not yet encountered it’s easiest to summarise this in a table as follows:
Operator | Description |
---|---|
($\ldots$) |
Parentheses |
** |
Exponentiation |
+x , -x |
Positive, Negative |
* , / , % |
Multiplication, Division, Remainder |
+ , - |
Addition, Subtraction |
So parentheses trump everything else, so 2**5.0/2
(16.0) is not the same as 2**(5.0/2)
(5.656854249492381) and that can require some careful thought at times!
Also pay attention when dividing by zero. Python won’t be able to compute any value and will return an error (which is sometimes also called an exception):
Notice that we have something new here: try: ... except: ...
. This is how we stop Python from breaking at the point where an expected error occurs. Without that try/except code at this point everything would come to a griding halt. We’ll cover exceptions in more detail later in Code Camp.
Replace the questions marks ???
in the following exercise with the appropriate code to purposufully cause a ZeroDivisionError
exception (again, feel free to use a calculator and you can run the code multiple times).
Python always tries to tell you what it thinks went wrong and this is the starting point for all debugging. When something goes wrong in a program this error is like the first clue that puts you on the trail of the ‘wrongdoer’: sometimes one clue will lead to another, and another, and another… sometimes one clue is all you need.
But regardless, if you ignore these clues and just put up your hand and say “It doesn’t work!” then we’re not going to be very impressed.
So we’ve seen some examples above of maths with integers (i.e. “whole” numbers) and maths with floats (i.e. “decimal” numbers). Both can be positive and negative (e.g. -1
or -254.32672
). Programmers, being lazy, often call integers ints because it’s faster and requires less typing.
Any operation involving a mix of floats and integers will always yeld a float. For example, compare the output for the code below, but note how the resulting data type varies with the operation.
Notice that last tricky bit: we’ll get to what int(...)
means later, but if you remember that programmers are lazy then you might realise that it must be short for integer and those parentheses must be telling Python to do something with the answer to change it from 3.14...
to 3
.
The reason for these slightly different answers is that Python is implicitly converting (sometimes called casting) the numbers between the two different data types. This conversion doesn’t happen with more complex bits of Python code, but for simple numbers Python tries to be helpful and save you the time and effort.
The integer-to-float conversion might seem a bit of a pedantic distinction, but imagine if you were programming a banking application: you would definitely pay attention to all those decimals!
Let’s start with calculating the area of a triangle. Here’s the equation for the area of a triangle: \[A = \frac{l_{base} * l_{height}}{2}\]
So lets work out for a triangle that has sides of length 10 and 20! If you type the maths correctly into the empty block below you should get the answer: 100
Now let’s work out the length of the hypotenuse of a right-angle triangle with the same side lengths as above: \[l = \sqrt{x^2 + y^2}\]
You might remember this as the Pythagorean Theorem, and you should get an answer of about 22.4.
Let’s move on to two last harder ones. Write a line of code to work out the area of a circle of radius 6. Here’s the formula: \[A = \pi r^2\] and you should get something around 113.1 as the area. Use 3.1412 for the constant pi.
Now work out the approximate radius of a sphere whose volume is 85. To do this, you’ll need to work backwards from the formula to calculate a volume… this might seem a little rough at first, but remembering how to rearrange a formula is really helpful for computational thinking!
So what do you have to do to this formula: \[ V = \frac{4}{3} \pi r^3 \]
Here’s a hint to get you started: \[ r^3 = \frac{3}{4 \pi} V \]
Also: remember that you’re going to need to work with decimal numbers, not whole numbers and write your code accordingly! You should get a final answer of about 2.7.
There are a lot of different ways that you could write this formula as code and still get the right answer. Getting the right answer is 50% of the job. The remaining 50% is about doing it in a way that is elegant and easy to read… as get further into the term we’ll point out how elegance and legibility (also: commenting) matter.
OK, so that’s the basics of numbers. What about text?
In most programming languages, text and words are called strings, which is really a fancy word to say a sequence of characters enclosed in single- or double-quotes (’ or “). This might seem like stating the bleedin’ obvious but this is a really, really important idea…
"235op\!u\$nlkgfd8 wp8ty fgdoy8p waklj ag9up0"
is a string. So is:
"If music be the food of love, play on; Give me excess of it, that, surfeiting, The appetite may sicken, and so die."
(Twelfth Night, Act 1, Scene 1, 1–3)
The thing is that computers can’t automatically distinguish between Shakespeare and the work of a monkey hitting keys at random. As long as they are both marked out by single- or double-quotes then as far as the computer is concerned they are strings. So even to ask the computer how many words there in the first 3 lines of Twelfth Night means we have to ‘teach’ the computer what a word is by giving it rules to recognise the start or end of one, and even how to recognise the start and end of a line so that it can find the first three of them!
As before, we’re using the print()
command here to show each of the outputs. Without print-ing the output we’d only see the results of the last line of code (print(type(t2))
).
Notice that now we’ve got two commands and that they are ‘nested’ one inside the other? So we are asking to tell us the type of t1
(using type(t1)
) and then we ask it to print
the results of that type command. This confirms that t1
and t2
are strings.
Although you can technically use either type of quote ('
or "
), it is generally better to use double-quotes as a way to prevent errors if a single-quote is contained in your string:
If you try to run the code above you’ll get a ‘syntax error’ message. Notice also that the colour-coding of the string looks… odd: some bits are blue, some bits are green, some are grey, unlike the double-quoted example above. We’ll come back to how to read errors like these in more detail in the next lesson, but again Python is giving us hints about where we might have made a mistake.
What do you do if your string contains double-quotes and single-quotes? That’s where the ‘backslash’ (\
, a kind of ‘reverse division’ symbol) comes in handy. The backslash is how we ‘escape’ characters so that we can do ‘special’ things with them when they should normally do something else.
In the example below, the backslash in front of the apostrophe in I'm
says “Don’t treat this as ‘normal’ single-quote that means the end of the string, treat it as a literal single-quote in the middle of a longer string marked out by single-quotes.
print('I\'m using the backslash.')
print('I\'m also using the backslash \'\\\' to escape the error normally caused by having single-quotes.')
I'm using the backslash.
I'm also using the backslash '\' to escape the error normally caused by having single-quotes.
Let’s look at this a little more closely:
"I'm using the backslash"
but you get the point."\'"
). But what’s happening with "\\"
? Well, we need an extra backslash in front of the backslash so that the computer knows to print a literal backslash (we are ‘escaping’ the normal function of a backslash to escape the character immediately after it) instead of reading it as escaping the one in front of the single-quote.That’s pretty weird, but just to show you what’s happening here it is without that extra backslash:
If you run the code above, you’ll see another error! Also notice that in the two lines of code, in the first the whole line is in one colour (meaning the computer can see that it’s all one string), but in the broken example right before this the text changes colour once we get to “to escape the error…” (meaning that the computer doesn’t see it all as one string).
The escape symbol crops up in a lot of other circumstances. For example, what if we wanted to tell Python that a string contains a newline (i.e. that the string is split across one or more lines, like our Shakespeare quote above should be)?
Remember that programmers are always lazy when given half a chance and so they figured out that the easiest way to mark a newline was \n
. They used ‘n’ because it is fairly easy to remember that that means ‘newline’, and the backslash ‘escapes’ us from the simple world where an ‘n’ is the letter ‘n’ into the computer’s world where ‘n
’ is ‘n’, but \n
is a newline:
See how that wraps the text on the \n
? Also note that the computer is printing exactly what we told it to do: I kept a space between the \n
and the start of the next line. If you squint, then you can see that lines 2 and 3 are indented by the width of one space character. There’s also an extra space after ‘surfeiting’ before the comma.
We say this a lot later too, but you might as well start learning this fact now: spaces in a string matter. To a computer " A string"
and "A string"
are not the same. Notice that there is a single space in front of the first ‘A’. As human beings we tend to just skip over that space (especially if it’s hard to see), but to a computer one string starts with ‘A’ and the other with ’ ’, so they are completely different.
Further, numbers and strings are not the interachangeable: "2016"
is not the same as 2016
. The first is a string that happens to contain the characters 2, 0, 1, and 6. The second is an integer number one larger than 2015.
As you can see from running the code above, it’s a bit annoying that they look the same when we print them. But if you run the next lines of code (after thinking about what they might do), you’ll see how Python tries to be helpful with its errors:
See how the first line of code prints 2016
, but the second line of code (which tries to add together a string "2015"
and the number 1
) gives you an error about a problem with str
(i.e. string) and int
(i.e. integer) ‘concatentation’. More on concatenation in a minute.
Obviously, having a lot of \n
markers would be hard to read and a potential problem if you wanted to copy and paste the text into a different application. If you have a long block of text then you can avoid the whole issue by putting your text inside triple-quotes:
As with numbers, there are many things that you can do with strings. The simplest, however, is like addition (which is why it uses a +
): when you add strings together you get a new, longer string that contains the characters of the original strings. This is usually called concatenation:
So just like you would do to add two numbers together, we can add “String1” and “String2” together to get “String1String2”. But notice that the +
operator doesn’t insert whitespace (i.e. a ’ ’ character) or anything else. It just sticks the two strings together exactly as they are.
And just like we can add together a whole set of numbers, we can add together a whole set of strings as in the second line beginning “Hey, looks like…”
If you use the multiplication operator (*
) on a string then you will multiply the string by the value of the multiplier.
What do you think will be the output of this code? (Work out your answer before running the code)
Now, why do you think the next example below doesn’t work? (Read the error output if you’re not sure what’s going on.)
So far, everything we’ve done was about performing some kind of calculation on an integer, float, or string, and then showing the result. Given that a lot of programming doesn’t involve solving everything in one line of code, how do you save an answer so that you can (re)use it later? Let’s start with the first true programming concept: the variable.
If you have studied other programming languages before then the concept of the variable will be so familiar to you that it’s hard to remember even having to learn it! Some people think of a variable as “a box” that contains values that we want to store and retrieve in the future. For the novice, however, we think it might be more useful (though less technically correct) to think of a variable as the label of the box: the label is how we remember what we put in the box and where we put it.
Let me try to explain: the computer stores ‘information’ in lots of places (in memory, on the hard drive, etc.), but it doesn’t use an addressing system that you or I would be able to understand. Memory addresses look something like 140302757291280
or '0x7f9ac8026510'
. Those numbers tell the computer “Go look in this place for what to do when the mouse is clicked” or “Go look up in that place what to do when someone asks you to add together 1 and 5”. Variable names are like the human-readable postal addresses on the outside of the box that the computer uses to deliver/return contents (what we put inside the box).
Here’s an example:
Hmmmm, nothing printed out this time…
That’s because this time we gave Python a box with the label “result” into which to put the result of multiplying -2 and 10.
You can change the type of result
to a float:
Check it out! We assigned the outcome of -2 * 10
to a variable called result
; then we did something else (printed out a string); and then we printed out the value of the variable and the computer remembered!
And variables can be copied using the =
operator in the same way that the result of the maths operation above could be assigned to a new variable called result
.
Cool, both variables have the same value! We assigned the result of 1 * 5
to a variable named myFirstVariable
and then we assigned this value to a second variable called mySecondVariable
.
But why is this called assignment (or, in plain English, copying)? Well what happens when I change the value stored in myFirstVariable
? Will the second change as well?
Whoa! mySecondVariable
didn’t change and still remembers what we assigned to in the first time. Basically, we took the myFirstVariable
label and attached it to a different box.
As the Python Programming Wikibook explains, when you assign a variable you are associating a variable (a label) to an object (a box) which is stored somewhere in the memory. So when you assign a new value to a variables you are not overwriting the old values but simply “moving” the label from one box to another. By analogy, we peeled the myFirstVariable
off of the box containing the value 5
and attached it to a box containing the value 2
. But mySecondVariable
was completely unaffected; it’s still attached to the box containing 5
.
That’s why in Python variables have a name
, a data-type
and a value
.
Name | Data Type | Value |
---|---|---|
myFirstVariable | integer | 2 |
mySecondVariable | integer | 5 |
Change the code below by replacing the question marks ???
to make it work (i.e. not produce an error). So we want to:
How do you choose a variable name (i.e. address label) in Python?
Here’s a short list of the rules:
myVar2
)2myVar
)my_var_2
)m2
or mySecondVariableIsReallyLong
)print
) or, rather, you can but you will start to get really strange problems in your code because you just changes what that variable/function does.So this block of code below will run:
But this block of code will not:
Notice how the code has been coloured the text so that the ‘1’ in what we wanted to make the variable name stands out? Again, that’s Python trying to help us figure out what is going wrong, but it requires that you look closely at the output of the error message.
Remember that we said the string " Some text"
and the string "Some text"
are different because the space at the start of the string changes everything? The same sort of strict checking is true for variable names: in short, Python is case-sensitive!
This means that this_var
and This_var
are two different variables and can refer to two different boxes:
As for many issues related to Python’s style, it is good practice to always refer to the offical PEP 8 – Style Guide for Python Code
For more examples of Python variables check out also OpenTechSchool’s intro to Python
Now that we’ve had a taste of the fantastic Python programming world, let’s solidify our newly acquired skills with a final round of excercises.
Look at the following example (and its output):
Similar to the example above, in the code cell below:
new_satellite
with value Landsat
Replace the questions marks ???
in the following exercise with the appropriate code to make it work
Landsat is a bit generic, the correct name is Landsat 8. How would you put together these two different Data Types? Remember what we’ve seen about casting? Edit the code below to make it work.
According to its Wikipedia page Sputnik 1 was a 58 cm diameter polished metal sphere. If a cm = 0.393700787 inches what was its diameter in inches? Edit the code below to make it work.
Wat was its volume (in cubic cm)? # NOTE: the first line below we are “importing” the math
module and assigning to a variable PI
the value of pi (3.14…). Edit the code to make it work.
Hmmmm… something’s broken in the following line of code; can you spot the error(s)? Hint: remember what we said about different data types…
# The error message indicates a type error, as we can only concatenate string
# The code should work by including "" to the numbers
print(new_satellite + " has a Near Infrared (NI), \
which band captures light in the wavelength from "+
"770" +
" to " +
"900" +
" nanometers." )
Landsat has a Near Infrared (NI), which band captures light in the wavelength from 770 to 900 nanometers.
In this excercise you’ll dip a toe in the wonderful world of web maps!
We are going to create a geographic marker (a pin on the map!) on top of OpenStreetMap (OSM) to visualise UCL CASA location.
To do so we’ll have to create a string representing a web URL
(that’s the address you type in your browser when your surf the web) pointing to OSM website.
Now, as you can see there are two variables containing CASA’s Longitute/Latitude coordinate position. You will need to use them within the variable CASA_position
. Unfortunately they are in the wrong data type! Also, there might be something missing in the code.
HINT: To convert (cast) a float
to a string
use the str()
function (we haven’t talked about functions yet, but see if you can work it out). You’ll also need to think about how to concatenate strings?
Replace the ???
in the code below to make it work.
# UCL CASA coordinates
# What format are they in? Does it seem appropriate?
longitude = -0.13604732328636063
latitude = 51.52199740741031
#cast the floats to strings
lon = str(longitude)
lat = str(latitude)
# CASA marker
CASA_position = "https://www.openstreetmap.org/?mlat="+lat+"8&mlon="+lon+"#map=15/"+lat+"/"+lon
print(CASA_position)
https://www.openstreetmap.org/?mlat=51.521997407410318&mlon=-0.13604732328636063#map=15/51.52199740741031/-0.13604732328636063
Click on the output (or copy and paste it into your browser) and behold! You’ll be flying to CASA.
For the most curious among you.
On this lesson’s topic: - StackOverflow: In Python, why can a function modify some arguments as perceived by the caller, but not others? - StackOverflow: Is it possible only to declare a variable without assigning any value in Python? - YouTube Video 1 - YouTube Video 2 (slightly longer)
General list or resources - Awesome list of resources - Python Docs - HitchHiker’s guide to Python - Learn Python the Hard Way - CodeAcademy
The following individuals have contributed to these teaching materials: - James Millington - Jon Reades - Michele Ferretti - Zahratu Shabrina
The content and structure of this teaching project itself is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 license, and the contributing source code is licensed under The MIT License.
Supported by the Royal Geographical Society (with the Institute of British Geographers) with a Ray Y Gildea Jr Award.
This lesson may depend on the following libraries: None