Skip to content
Snippets Groups Projects

Corrections - Tom

1 file
+ 14
0
Compare changes
  • Side-by-side
  • Inline
+ 14
0
%% Cell type:markdown id: tags:
# First Steps
We can use python in a variety of ways:
The simplest is to invoke the interactive shell by just typing ```python``` on the command line. This will allways work whenever we have an python interpreter installed and we will get the characteristic prompt ```>>>```. However, it is not very convenient to use as it does not allow a rich history or editing. You can leave this shell by either typing ```quit()``` or ```CTRL+D``` (for EOF: End-Of-File). ```ipython``` is an enhanced interactive shell that is a good way to interact with python whenever we need to do so from the command line.
If we have a python program in a file (e.g. my_program.py), we can run this program via ```python my_program.py```.
Another - very popular - way to use python is via Jupyter Notebooks (such as this one). The notebooks consists of separate "cells" where we can mix, for example, documentation or instructions (text, images), and code together with the output of the code.
Each cell can be executed and the code in this cell is then passed to the python interpreter, executed and then the resulting output (if any) is displayed.
This is a great way to explore and work interactively.
However (and there is always a "however") - the cells have a "state" in which the current status is captured and, therefore, the order in which you execute the cells matters. As always: use with care...
But now, let's start!
%% Cell type:markdown id: tags:
## Python as a pocket calculator
Let's do a simple sum, say, what is 3 + 4
%% Cell type:code id: tags:
``` python
3+4
```
%% Output
7
%% Cell type:markdown id: tags:
We can also do the other basic operations, such as multiplication, division
%% Cell type:code id: tags:
``` python
3/2
```
%% Output
1.5
%% Cell type:markdown id: tags:
Now multiply 25 by 25.
Note: lines starting with "#" are comments and ignored by python.
%% Cell type:code id: tags:
``` python
# .... your code here....
```
%% Cell type:markdown id: tags:
Next, we want to calculate the circumference of a rectangle. The long side is, say, 10cm long, the short side 7cm.
We could write it like this:
%% Cell type:code id: tags:
``` python
2*10+2*7
```
%% Output
34
%% Cell type:markdown id: tags:
However, this would be very inconvenient if we were to look at more rectangles.
We can use variables to store the values of the length of the sides:
%% Cell type:code id: tags:
``` python
short_side = 7
long_side = 10
```
%% Cell type:markdown id: tags:
First, we notice that we do not need to declare variables - we "simply" assign them use them.
Also, the above cell does not produce an output.
We can use the ```type()``` command to see that python has indeed determined that this is an integer variable.
%% Cell type:code id: tags:
``` python
type(short_side)
```
%% Output
int
%% Cell type:markdown id: tags:
We can see that python has inferred that we are using integers here. Python uses the concept of "dynamic typing" which means that the type of the variable is only determined at run-time (when the code is excecuted). Other languagues, such as, e.g. C++, use "strong typing" where the type of the variable has to be defined when the code is written (e.g.: ```int short_type = 7```).
As always - dynamic typing has advantages and disadvantages: It is obviously very easy to use as we see above and we can also write quite flexible code that operates on a range of types. For example, if we had written ```short_side = 7.0``` we would have obtained a float variable. Our code would do the same, in python, it even is the same code, in other languages, we have to be more stringent.
On the other hand, strong typing also allows to check for incompatible types even before the code is executed.
> __A word on naming variables:__
>
> Try to name the variables such that their name reflects their purpose. We could have written ```x=7``` and ```y=10``` but then we would probably have forgotten what ```x``` and ```y``` stand for immediately. we could also have written ```short=7``` and ```long=10```. This would have been a bit better - but if we have a few more variables, we would probably wonder what we refer to as ```long``` and ```short```...
>
> Many conventions exist regarding variable names. Some use CamelCaps (```ShortSide```), in python, most follow the convention to use underscores (```short_side```).
Back to the problem at hand, we wanted to calculate the circumference. Best to store that in a variable as well.
%% Cell type:code id: tags:
``` python
circumference = 2 * short_side + 2 * long_side
```
%% Cell type:markdown id: tags:
We notice that this cell does not have an output now.
To get the value of the variable, we can use the ```print()``` statement to print the value to the output or screen:
%% Cell type:code id: tags:
``` python
print(circumference)
```
%% Output
34
%% Cell type:markdown id: tags:
This works, but it would be nice to answer the question "What is the circumference of the rectangle" with a complete sentence (much as you did in primary school, presumably).
The simplest way would be to print the string ```The circumference in cm is:``` and then the value.
Note that we can separate the two by a comma (```,```). The print statement then prints all the arguments we give it one after another.
%% Cell type:code id: tags:
``` python
print('The circumference in cm is:', circumference)
```
%% Output
The circumference in cm is: 34
%% Cell type:markdown id: tags:
However, the print statement is much more powerful and we can place, for example, the value in the middle (before the unit).
You can find more details in the official [format documentation](https://docs.python.org/3/tutorial/inputoutput.html#the-string-format-method).
The general format is:
```print('output string {<variable and qualifier>}.format(variable1, variable2, ...))```
So here:
%% Cell type:code id: tags:
``` python
print('The circumference is {} cm.'.format(circumference))
```
%% Output
The circumference is 34 cm.
%% Cell type:markdown id: tags:
Another possibility is to use f-strings, which were introduced in Python 3.6.
%% Cell type:code id: tags:
``` python
print(f"The circumference is {circumference} cm.")
```
%% Output
The circumference is 34 cm.
%% Cell type:markdown id: tags:
Exercise: extend the print statement and include the long and short side as well.
%% Cell type:code id: tags:
``` python
# ... your code here ....
```
%% Cell type:markdown id: tags:
So far we have used integer values. Now we take real valued variables ("float").
Repeat the exercise but now calculate the circumference of a circle.
When you print out the result, use only two significant digits in the printout.
First, think about which variables you want to use. Then calculate the circumference and print the result.
> __Note:__
>
> Python does not know the value of pi, we'll define it here for the sake of this exercise.
> You also note another coding convention: Whenever we define a number or constant to use in our code, we use captitals to signify this.
%% Cell type:code id: tags:
``` python
MY_PI = 3.141592653589793238
# .... your code here ...
```
%% Cell type:markdown id: tags:
Your output should look similar to:
``` The circumference of the circle is 3.14 cm```
%% Cell type:markdown id: tags:
The most basic types are:
- int (integer)
- float (real valued)
- string
- boolean (True / False)
%% Cell type:markdown id: tags:
There are two ways we can define strings, either with single quote or with double quotes.
However, we cannot mix the two.
%% Cell type:code id: tags:
``` python
my_string = 'This is a string.'
my_other_string = "This is also a string."
print(my_string)
print(my_other_string)
```
%% Output
This is a string.
This is also a string.
%% Cell type:markdown id: tags:
We can convert between these types using ```int( number)```, ```float (number)```, ```string (number)```
%% Cell type:code id: tags:
``` python
number = 42
print('This is the number {} as a {}'.format(number, type(number)))
float_number = float(number)
print('This is the number {} as a {}'.format(float_number, type(float_number)))
string_number = str(number)
print('This is the number {} as a {}'.format(string_number, type(string_number)))
```
%% Output
This is the number 42 as a <class 'int'>
This is the number 42.0 as a <class 'float'>
This is the number 42 as a <class 'str'>
%% Cell type:markdown id: tags:
# As a final note:
Look at the following code:
%% Cell type:code id: tags:
``` python
shortside = 10
long_side = 15
circumference = 2 * short_side + 2 * long_side
print('The circumference is {} cm.'.format(circumference))
```
%% Output
The circumference is 44 cm.
%% Cell type:markdown id: tags:
Hm....
we would have expected the output to be 50 cm (2 \* 10 + 2 \* 15) - but it's 44 cm.
Note that in the cell above we have written ```shortside = 10``` when we assigned the variable, however, in the calculation of the circumference we have used ```short_side```.
Earlier, we have indeed defined and used a variable called ```short_side``` - and this is the variable that is used here. These kind of typos are often the cause of a lot of bugs.
By adhering to best coding practices we can reduce that this happens too much.
>Jupyter notebooks are particularly vulnerable to these kind of bugs as they can easily become quite long and all variables from each cell is stored. This can lead to very confusing behaviour if we execute cells in different orders and jumpt between cells.
>
> We will use Jupyter notebooks throughout the course for the majority of exercises - mainly as they allow you to participate from a browser and you do not have to set a development environment up on your computer. However, we will also discuss how to write code in less error-prone ways.
Loading