Getting started with Python

Overview:

  • Teaching: 10 min
  • Exercises: 5 min

Questions

  • How do I write and execute code?
  • How do I print to the screen?
  • How can I perform calculations with Python?

Objectives

  • Understand how to write to the screen.
  • Understand how to use mathematical operators to perform calculations

Hello World!

Convention dictates that everyone's first program should be hello world. While this seems of limited use it is really important on several counts:

  • It shows that we can write code
  • It quickly tests our ability to write legal code
  • It shows us how to get output from our programs, which is the point in the long run.

Input the follwing code and press SHIFT+ENTER to execute.

In [1]:
print("Hello world!")
Hello world!

print(string)

If your code has executed correctly you should see the output Hello World!. There are a couple of things to point out here:

  • We have used a built in function print, to print the text Hello World! to the screen
  • We have put the text we want to print in double, " or single, ' quotes.
  • You can try both options but they must be used consistently.
  • In the version of python we are using, everything we want to print must be contained in (, ), brackets/parentheses.

As a result:

In [2]:
print('Hello Drew!')
Hello Drew!

executes correctly, but

In [3]:
print("Hello anyone!')
  File "<ipython-input-3-0ab50b600b96>", line 1
    print("Hello anyone!')
                          ^
SyntaxError: EOL while scanning string literal

and

In [4]:
print "Hello anyone!"
  File "<ipython-input-4-e24e65dc5b9e>", line 1
    print "Hello anyone!"
                        ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello anyone!")?

raise SyntaxErrors. The messages are Python's way of trying to tell you what it thinks is wrong with the code you have written. Sometimes these messages can be quite long, so generally it is best read them from bottom to top.

In the first case the error message is EOL while scanning string literal, which needs some explanation.

  • EOL means End of line and in this context means Python reached the end of the line (while scanning) without having read a complete command.
  • string literal references that Python, and programming languages in general refer to text as strings (of characters). We will use this term a lot.
  • strings must be contained in matching pairs of quotes, the first indicates the start of the string, the second its end.

In the second case, Python has done a really good job of telling us it thinks the problem is. Missing parentheses in call to 'print'. Did you mean print("Hello anyone!")?, yes we did forget the parentheses and the suggested corrections is what we meant to type.

Save your work and ask for help

During this course we recommend that you save your work so that you can return to the lesson to go over material and remember what worked and what didn't. Everyone makes mistakes coding, as soon as you embrace this and learn from it you will make progress. You can save your notebook using the usual disk symbol in the top left of the notebook.

If you are stuck ask for help, demonstrators are here to help, and while we all started coding once, whenever you are doing something new we all need assistance!

Using Python as a calculator

After saying hello to the world let's see if we can use Python to perform some calculations, afterall this is what computers are supposed to be good for. Let's try a couple of examples:

In [5]:
print(4+2)
6
In [6]:
print(3-1)
2
In [7]:
print(5*3)
15
In [8]:
print(6/3)
2.0

Math operators

These simple calculations have performed as we would expect, note that:

  • To perform multiplation we use the asterix * and divide a forward slash /.
  • Your output may be slightly different depending on the version of Ipython you are running

Your turn

Before trying these commmands think about what the output might be, then run them and see if you were correct:

  1. "Hello World!"
  2. print(42)
  3. 7+1
  4. 7.0+1
  5. 5/3
  6. 5.0/3.0
  7. 1/0
  8. 0/0
  9. 0.0/0.0
  10. 1 + 0.000001
  11. 1 + 0.0000000000000001 (that's 15 0s after the decimal place)

Solution

How are numbers represented

These exercises highlight a couple of features of programming languages which we will explore further in the next two episodes. Without getting into the specifics or philosophy of maths or computing, it is good to have an appreciation for what is going on, how computers represent numbers and how they resolve undefined quantities.

1) As with the output of calculations if we just input a string, python will print this to the screen, note that the output is slightly different from before.

Programming languages have to represent numbers in a finite amount of computer memory and in order to enable this they typically have two classes of numbers: integers, the discrete values, and real numbers or floating point numbers, floats, the continuous number line.

Integers and floats are data types in the same way as the string that we saw earlier, except that rather than representing characters they represent numerical values. When Python performs a calculation it examines the values entered and what you are trying to do and makes a decision how to do it.

2) In order to print numbers we do not need to enclose them in parentheses, numerical values are different from strings of characters.
3) When we asked 7+1 the entire calculation could be evaluated as integers, 7, 1 and 8 are all integers.
4) In specifying 7.0+1 the 7.0 meant the whole calculation was treated as floating point, so the result was given as 8.0
5) and 6) When performing division, regardless of the representation Python cannot know what the result will be so assumes that it will be a float.
7) and 8) Integer division by zero is not defined.
9) Neither is floating point division by zero but the error is slightly different.
10) and 11) Only a finite amount of space, memory is available for representing numbers, for floating point numbers this means that the precision is limited. One result of this is that at a certain point adding a relatively small number to a relatively big one does not change the big one.

Note that differences between Python 2 and Python 3 mean that the results of these operations will change. This is why we run ipython3 to ensure we are using the correct version.

BODMAS

Evaluate the following expressions then check the result with Python

  1. 3 + 4 / 2 + 1
  2. (3 + 4) / 2 + 1
  3. 3 + 4 / (2 + 1)
  4. (3 + 4) / (2 + 1)

Solution

Key Points:

  • print( ) allows us to output to the screen.
  • When we make mistakes, python tries to help us work out what went wrong.
  • strings of characters need to be enclosed in pairs of quotes, either " " or ' '
  • Number are represented either as integers or floats and have a finite amount of memory available to them.
  • Undefined operations such as dividing by 0 raise errors to inform us there has been a problem.
  • Different programming languages (and versions) can have different behaviour that may affect how our programs work.