Introduction to programming with Python

What is computer programming?

Programming simply to create computer programs. We are surrounded by computer programs (or software) everywhere. For instance Microsoft Word, Mozilla Firefox and Photoshop. Other examples are all the apps you have installed on your smart phone. These examples are usually large complex programs, but most computer programs are much simpler and you will write your first program very soon if you continue reading.

To understand how programming works from a bird eye view you can play a game called Lightbot. The game is pretty self explainatory, so make sure you follow the instructions carefully! When programming it is extremely important to be precise.

TODO: Could explain more!

A computer program is written in a programming language. There are many different programming languages. Lightbot uses a symbolic language where you use icons to create a program. In the following we are going to write code using Python instead. However, the principles you learned by playing Lightbot are the same. Below is an illustration of the workflow we use when we are programming. Do you see how similar the different steps are to the steps you performed when you played Lightbot?

Alt text

Alt text

Installation

TODO Fill in! If this is for E+ only maybe something about Sage?

Your first program

Our first program only consist of one line:

When we run the code “Hello world!” is printed to the screen. This is because we used the key word \(\texttt{print}\), which tells the computer to write what follows to the screen. Notice that we use quotes at the beginning and end of “Hello world”. This is done such that the computer can distinguish text from code. To make it easier for the programmer to distinguish between text and code they are shown in different colors.

The text “Hello world!” is chosen arbitrarely. Try to change the text between the quotes and see what happens!

Math

In Python and most other computer languages the basic mathematical operators are written as \(+, -, *,\) and \(/\). In python exponentials are expressed by a double asterisk (\(*\)\(*\)) notation. Lets show some examples:

When we run the code the results are just as expected apart from the division. The reason why 2 divided by 3 is zero will be described in the section below about types.

TODO: The following shoud be part of and if/else section.

Other useful operators are greater-than (>), less-than (<), greater-than-equal (>=), and less-than-equal (<=).

If we ask this as a question: Is 7 bigger than 5? You can answer either yes or no. In other words the assertion may be true or false, which is what you see on the screen when you run the program. Play around, try various combinations, and guess the result!

Finally, we can improve the print command such that the output is easier to read:

As before we put quotes around the part that should be interpreted as text, after the text we add a comma and then we continue writing the math. The numbers and mathematical operators will be interpreted as code when we execute our program.

Variables

Variables are names we give in our program such that the computer remember the variable and we can use it later in our program. Here is an example

In the first line we create a variable called \(\texttt{name}\), which contains the name Jonas. Think of the variable as an empty box called \(\texttt{name}\). Then we put the name ‘Jonas’ into the box, which is stored in the computers memory. Similarly, the next line of code defines a variable called \(\texttt{age}\), which contains the number 23.

Change the variables such that they contain your name and age, then run the program. What happened? Nothing, or at least your terminal is empty. Python has only created the variables. If you would like to see them you can add a \(\texttt{print}\) command at the end of the program.

What happens when you run the code below?

Why is not the result printed to the screen ‘Jonas’ and ‘23’? This is because Python interpret the code as textstrings and not as variables when you use quotes.

Note that if you try to create two variables with the same name, the first variable will be overwritten by the second. So what will happen when you run the code below?

Types

By now you learned that variables have a name and a content, but they also have another property namely a \(\texttt{type}\). When Python creates a variable it identifies the type of the content. In the last example we created the variable name, which contains a text string and age which contains a number. Python remember this information; \(\texttt{name}\) is a text string and \(\texttt{age}\) is a number.

To check which type a variable has we can use the command \(\texttt{type}\). Here is an example:

In this program we first create four variables then the type of each variable is printed. The results show that location and day has the type ‘str’, which is an abbreviation for string. The variable year has the type ‘int’, which means that it is an integer. Finally, temperature has the type ‘float’. Thus python distinguishes between floats and integer. In the section about mathematical operators we got zero when we divided 2 by 3. This is because both 2 and 3 have the type ‘int’ and therefore also the result will have the type ‘int’. If we use float numbers instead we get the expected answer. Here is an example to show the difference:

In the last line we divide a float by an integer. Note that the result has the type \(\mathit{float}\).

Lists

Until now you have learned that variables has a name, a content, and a type. Now it is time to introduce a different type of variables: lists. If we want our program to remember the names of all the students in a class. We can create one variable for each student or we can create one variable containing all the students. The latter is called a list and here is an example:

Here we have used square brackets to define a list, and within the brackets we have written 5 names separated by a comma. Further, every name is defined as a string. When you have defined a list you can print it and check the type:

You can also check how many elements there is in your list by typing

After we have defined a list such as students

We can access the elements in the list through the index of every element:

Here \(\texttt{students[0]}\) means the first element in the list, which is ‘Jake’, while \(\texttt{students[3]}\) is the 4th element in the list, which is ‘Lucy’. Note that Python starts counting at zero! This might seem strange, but it is just a definition we have to get used to.

If we want to we can also change the elements within the list. If it turns out that we made a mistake and ‘Alexander’ should be ‘Alex’. We can overwrite the 5th element in the list as follows

When we print the list we see that the last element is changed, just as we wanted.

It is also possible to add elements to the list. For instance if we forgot one of the students in the class you can add her by typing

When we add items to a list they always appear at the end.

In some cases it makes sense to create and empty list and then add elements afterwards. Here is a list, which is initially empty and then filled with numbers

Arrays

Loops

A loop is a piece of code which repeat itself. If we want our program to perform the same task many times in a row we need a loop. There are to types of loops, namely for-loops and while-loops. Here we are only considering \(\texttt{for}\)-loops.

A for-loop repeats a piece of code for every element in a list. Again we use the list with students. Now we want to print the names and how many characters each name has:

The code is executed for every name in the list, i.e., since the list has 5 elements the code is exectuted 5 times.

The first line \(\texttt{for name in students:}\) creates a loop over all elements in the list \(\texttt{students}\). In each pass of the loop, the variable \(\texttt{name}\) refers to an element in the list, starting with \(\texttt{students[0]}\), proceeding with \(\texttt{students[1]}\), \(\texttt{students[2]}\), and so on until we reach the last element in the list.

The \(\texttt{for}\) loop specification ends with a colon, and after the colon comes a block of statements that does something useful with current element. Note that the block must be intended, this is an important feature in Python. This might be difficult to remember, but you will get used to it.

Here is antother example where we are adding the number from 1 to 10:

If we want to loop over the numbers 1 to 1000 instead it will take long to write down the list of numbers. Fortunately, there is a function called \(\texttt{range}\) in Python, which can do this job for you. Range takes two arguments (\(\texttt{range(start, stop)}\)) and returns a list of numbers (integers) from start to stop. Here is to examples:

Note that the last number is not included! We may also add a third argument, this argument tells us how large the step between the numbers should be. Here is a few examples:

\(\texttt{range}\) is very useful in our \(\texttt{for}\) loop

Plotting

Handling errors