Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • linigodelacruz/practicum-lecture-notes
  • stephandehoop/practicum-lecture-notes
  • saghajani/practicum-lecture-notes
  • jeroenkalkman/practicum-lecture-notes
  • python-for-applied-physics/practicum-lecture-notes
5 results
Show changes
Commits on Source (104)
Showing
with 954 additions and 204 deletions
...@@ -3,6 +3,7 @@ outputs: ...@@ -3,6 +3,7 @@ outputs:
- conda install jupytext -c conda-forge - conda install jupytext -c conda-forge
script: script:
- "jupytext */Notebook*md Outline\\ of\\ notebooks.md --to notebook" - "jupytext */Notebook*md Outline\\ of\\ notebooks.md --to notebook"
- "jupytext Additional*/*md --to notebook"
artifacts: artifacts:
paths: paths:
- "*/Notebook*ipynb" - "*/Notebook*ipynb"
...@@ -11,6 +12,8 @@ outputs: ...@@ -11,6 +12,8 @@ outputs:
- "Notebook*/*png" - "Notebook*/*png"
- "Notebook 5/exercise_data.dat" - "Notebook 5/exercise_data.dat"
- "Notebook 5/v_vs_time.dat" - "Notebook 5/v_vs_time.dat"
- "Notebook 5/example2.dat"
- "Outline of notebooks.ipynb" - "Outline of notebooks.ipynb"
- "Additional*/*" - "Additional*/*ipynb"
- "Additional*/*png"
name: Lecture_Notebooks name: Lecture_Notebooks
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Additional Programming Concepts in Python # Additional Programming Concepts in Python
In this notebook, you will learn about additional programming concepts in Python. They are not part of the learning objectives of the course, but you may run into them at some point, or wonder what they are, or find them fun and useful if you already have some programming experience. In this notebook, you will learn about additional programming concepts in Python. They are not part of the learning objectives of the course, but you may run into them at some point, or wonder what they are, or find them fun and useful if you already have some programming experience.
*(Much of this material we wrote up in an earlier version of the notebooks, but then moved here when we tweaked the course to fit in the time we have available.)* *(Much of this material we wrote up in an earlier version of the notebooks, but then moved here when we tweaked the course to fit in the time we have available.)*
## Tuples ## Tuples
### What is a tuple? ### What is a tuple?
The first more complicated data structure we will discuss is a `tuple`. A tuple is a collection of values inside curved brackets. Here is the basic syntax for making a tuple: The first more complicated data structure we will discuss is a `tuple`. A tuple is a collection of values inside curved brackets. Here is the basic syntax for making a tuple:
``` ```
my_tuple = (a, b, c, ...etc...) my_tuple = (a, b, c, ...etc...)
``` ```
As a concrete example, this will create a tuple of three integers: As a concrete example, this will create a tuple of three integers:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
tup1 = (5,6,7) tup1 = (5,6,7)
print(tup1) print(tup1)
``` ```
%% Output
(5, 6, 7)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Like the other data types we've see, we can see the tuples we create using `%whos`: Like the other data types we've see, we can see the tuples we create using `%whos`:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%whos %whos
``` ```
%% Output
Variable Type Data/Info
-----------------------------
tup1 tuple n=3
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Tuples are like lists, but behave a bit differently than python lists. In fact, we've already seen tuples before in the previous notebook when we were looking at `for` loops! Tuples are like lists, but behave a bit differently than python lists. In fact, we've already seen tuples before in the previous notebook when we were looking at `for` loops!
If you are given a tuple, you can check how long it by using the `len()` function built into python: If you are given a tuple, you can check how long it by using the `len()` function built into python:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
len(tup1) len(tup1)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Note that tuples do not have to contain integers, they can contain any type of data: Note that tuples do not have to contain integers, they can contain any type of data:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# A tuple of strings # A tuple of strings
str_tup = ('foo', 'bar') str_tup = ('foo', 'bar')
print(str_tup) print(str_tup)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Different than how numpy arrays are typically used, tuples can even be mixed, with each element of a different type: Different than how numpy arrays are typically used, tuples can even be mixed, with each element of a different type:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
mixed_tup = (1, 1.05, 7+3j, 'foo') mixed_tup = (1, 1.05, 7+3j, 'foo')
print(mixed_tup) print(mixed_tup)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
And you can even have tuples of tuples: And you can even have tuples of tuples:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
tup_of_tup = (str_tup, mixed_tup) tup_of_tup = (str_tup, mixed_tup)
print(tup_of_tup) print(tup_of_tup)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Tuples support all the same indexing and slicing as arrays. Tuples support all the same indexing and slicing as arrays.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Tuples can also contain other tuples! If your tuple contains another tuple, like the example `tup_of_tup`, you can use the square brackets a second time to index into the tuple you extract by the first set of square brackets: Tuples can also contain other tuples! If your tuple contains another tuple, like the example `tup_of_tup`, you can use the square brackets a second time to index into the tuple you extract by the first set of square brackets:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(tup_of_tup) print(tup_of_tup)
print(tup_of_tup[0]) print(tup_of_tup[0])
print(tup_of_tup[0][0]) print(tup_of_tup[0][0])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Looping over tuples without using indices ### Looping over tuples without using indices
As mentioned briefly in Notebook 2, python `for` loops can also directly iterate over "iteratable" objects. As mentioned briefly in Notebook 2, python `for` loops can also directly iterate over "iteratable" objects.
The `tuple` (along with lists, which we will see in a bit, and numpy arrays, which we will see in the next notebook), is one such iteratable objecte. The `tuple` (along with lists, which we will see in a bit, and numpy arrays, which we will see in the next notebook), is one such iteratable objecte.
For example, to print all of entries of a `tuple` out in order, we can use directly following: For example, to print all of entries of a `tuple` out in order, we can use directly following:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for n in tup1: for n in tup1:
print(n) print(n)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
During each subsequent iteartion of the loop, the variable `n` will be assigned to the next item that is stored in the tuple. During each subsequent iteartion of the loop, the variable `n` will be assigned to the next item that is stored in the tuple.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Lists ## Lists
In this section, we will introduce a very commonly used data structure in python: the `list`. In this section, we will introduce a very commonly used data structure in python: the `list`.
A list is a list of values, like a `tuple`, but that is made using square brackets: A list is a list of values, like a `tuple`, but that is made using square brackets:
``` ```
my_list = [a, b, c, ...etc...] my_list = [a, b, c, ...etc...]
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
l1 = list(range(10)) l1 = list(range(10))
l1 l1
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Like tuples, you can extract single elements of the list using indexing, and extract portions of the list using slicing: Like tuples, you can extract single elements of the list using indexing, and extract portions of the list using slicing:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(l1[0]) print(l1[0])
print(l1[0:5]) print(l1[0:5])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
OK, so far so good. But if I have `tuple`, why would I ever want a list? OK, so far so good. But if I have `tuple`, why would I ever want a list?
### Lists vs tupples: Tupples are "immutable", lists are "mutable" ### Lists vs tupples: Tupples are "immutable", lists are "mutable"
This is a bit of python-speak for saying that you cannot change the values of a tupple, but you can change the values of a list. This is a bit of python-speak for saying that you cannot change the values of a tupple, but you can change the values of a list.
What does this mean? It means if I have a list `[5,6,7]` and I want to change the last number in my list to an 8, I can just directly do this: What does this mean? It means if I have a list `[5,6,7]` and I want to change the last number in my list to an 8, I can just directly do this:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
l1 = [5,6,7] l1 = [5,6,7]
l1[2] = 8 l1[2] = 8
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
If I try this with a tuple, I will find that I can't do it! If I try this with a tuple, I will find that I can't do it!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
t1 = (5,6,7) t1 = (5,6,7)
t1[2] = 8 t1[2] = 8
``` ```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-9c8e47fcf882> in <module>()
1 t1 = (5,6,7)
----> 2 t1[2] = 8
TypeError: 'tuple' object does not support item assignment
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Because of this functionality, **lists are much more powerful as we can change them once we've made them!** Because of this functionality, **lists are much more powerful as we can change them once we've made them!**
In addition to changing lists by individual indexing, we can also change whole parts of the list using slicing: In addition to changing lists by individual indexing, we can also change whole parts of the list using slicing:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
l2 = list(range(10)) l2 = list(range(10))
print(l2) print(l2)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Replace three entries by zeros # Replace three entries by zeros
l2 = list(range(10)) l2 = list(range(10))
l2[4:7] = [0,0,0] l2[4:7] = [0,0,0]
print(l2) print(l2)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Remove entries from a list by replacing them with an empty list [] # Remove entries from a list by replacing them with an empty list []
l2 = list(range(10)) l2 = list(range(10))
l2[4:7] = [] l2[4:7] = []
print(l2) print(l2)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Functions for manipulating lists ### Functions for manipulating lists
In fact, our list object itself has functions built in that allow you to change it! Some examples of things we can do: In fact, our list object itself has functions built in that allow you to change it! Some examples of things we can do:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# This will add an element to the end of the list # This will add an element to the end of the list
l1.append(10) l1.append(10)
l1 l1
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# This will remove an element from the end of the list # This will remove an element from the end of the list
l1.pop() l1.pop()
l1 l1
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
There are many more functions built into lists, some of which you can find here: There are many more functions built into lists, some of which you can find here:
https://docs.python.org/3/tutorial/datastructures.html https://docs.python.org/3/tutorial/datastructures.html
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### The problem with lists for scientific computing ### The problem with lists for scientific computing
Lists look an awful lot like numpy arrays: why don't we just use lists? Lists look an awful lot like numpy arrays: why don't we just use lists?
In scientific computing, it is very common to want to perform numerical operations on <a href=https://en.wikipedia.org/wiki/Row_and_column_vectors>vectors and matrices</a> of numbers. And also, many times in experiments, the data you will take will be represented by a vector of numbers: for example, the position of a particle as a function of time. In scientific computing, it is very common to want to perform numerical operations on <a href=https://en.wikipedia.org/wiki/Row_and_column_vectors>vectors and matrices</a> of numbers. And also, many times in experiments, the data you will take will be represented by a vector of numbers: for example, the position of a particle as a function of time.
A vector is a collection of numbers in a one-dimentional array: A vector is a collection of numbers in a one-dimentional array:
$$ $$
x = [1, 2, 3, 4, 5] x = [1, 2, 3, 4, 5]
$$ $$
In Notebook 3, we already introduced python `list`s. A list is also a vector, right? It certainly looks the same! Why do we need something new? In Notebook 3, we already introduced python `list`s. A list is also a vector, right? It certainly looks the same! Why do we need something new?
The reason we need something new is that python `list`s are not designed to work in the same way as we expect vectors to from our mathematics classes. For example, in math: The reason we need something new is that python `list`s are not designed to work in the same way as we expect vectors to from our mathematics classes. For example, in math:
$$ $$
2x = [2,4,6,8,10] 2x = [2,4,6,8,10]
$$ $$
Let's check if this works with lists Let's check if this works with lists
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
l = [1, 2, 3, 4, 5] l = [1, 2, 3, 4, 5]
print(2*l) print(2*l)
``` ```
%% Output
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
This certainly does something, but it does not do what we want! It has made the list twice as long by appending two of them together! This certainly does something, but it does not do what we want! It has made the list twice as long by appending two of them together!
Also addition and subtraction doesn't work like we would expect: Also addition and subtraction doesn't work like we would expect:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(l+l) print(l+l)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Addition makes the list twice as long? And: Addition makes the list twice as long? And:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(l-l) print(l-l)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
And subtraction doesn't work at all...clearly, although they look a lot like vectors, in terms of mathematics, lists do not act much like vectors. This is one of the reasons numpy arrays were created. And subtraction doesn't work at all...clearly, although they look a lot like vectors, in terms of mathematics, lists do not act much like vectors. This is one of the reasons numpy arrays were created.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Dictionaries ## Dictionaries
Another useful data type in python is a "dictionary": Another useful data type in python is a "dictionary":
https://docs.python.org/3/tutorial/datastructures.html#dictionaries https://docs.python.org/3/tutorial/datastructures.html#dictionaries
At a basic level, a dictionary is a bit like a list that supports non-numeric indices. Dictionaries can be created using the curly brackets in python `{` and `}`. At a basic level, a dictionary is a bit like a list that supports non-numeric indices. Dictionaries can be created using the curly brackets in python `{` and `}`.
Here we will create an empty dictionary and start filling it: Here we will create an empty dictionary and start filling it:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
delft_lunch_rating = {} delft_lunch_rating = {}
delft_lunch_rating['greek olive'] = 10 delft_lunch_rating['greek olive'] = 10
delft_lunch_rating['brandmeester'] = 7 delft_lunch_rating['brandmeester'] = 7
delft_lunch_rating['aula'] = "expensive" delft_lunch_rating['aula'] = "expensive"
delft_lunch_rating['citg'] = "bad" delft_lunch_rating['citg'] = "bad"
delft_lunch_rating['doner'] = "good but a bit salty" delft_lunch_rating['doner'] = "good but a bit salty"
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
This is what our dictionary looks like: This is what our dictionary looks like:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(delft_lunch_rating) print(delft_lunch_rating)
``` ```
%% Output
{'greek olive': 10, 'brandmeester': 7, 'aula': 'expensive', 'citg': 'bad', 'doner': 'good but a bit salty'}
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
I can then look up values in my dictionary using the "keys": I can then look up values in my dictionary using the "keys":
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
delft_lunch_rating['aula'] delft_lunch_rating['aula']
``` ```
%% Output
'expensive'
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
There are also functions for getting all the keys: There are also functions for getting all the keys:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
delft_lunch_rating.keys() delft_lunch_rating.keys()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
My dictionaries can also hold lists if I want: My dictionaries can also hold lists if I want:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
delft_lunch_rating["greek olive"] = ['good', 10] delft_lunch_rating["greek olive"] = ['good', 10]
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Dictionaries are actually a way to implement a basic database in python (I use them in my grading scripts to look up the email addresses and student numbers of a given netid...) Dictionaries are actually a way to implement a basic database in python (I use them in my grading scripts to look up the email addresses and student numbers of a given netid...)
And the Jupyter notebook files actually store a list cells, and each cell consist of a dictionary that contains the text of the cell (and other fun things like metadata). You can see this in action using the <a href=https://nbformat.readthedocs.io/en/latest/api.html>nbformat</a> library, you can actually load a notebook file into your python kernel and poke around it to see what it looks like. And the Jupyter notebook files actually store a list cells, and each cell consist of a dictionary that contains the text of the cell (and other fun things like metadata). You can see this in action using the <a href=https://nbformat.readthedocs.io/en/latest/api.html>nbformat</a> library, you can actually load a notebook file into your python kernel and poke around it to see what it looks like.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Strings ## Strings
In notebook 1, we already saw strings as variable types. In notebook 1, we already saw strings as variable types.
It turns out that strings are not just simple (immutable) variables like `int`s and `float`s: `str`s are actually data structures that are indexable (like `tuple`s and `list`s). It turns out that strings are not just simple (immutable) variables like `int`s and `float`s: `str`s are actually data structures that are indexable (like `tuple`s and `list`s).
Strings are immutable, which means they cannot be changed. But they do have lots of built-in functions that can return a new string (or lots of other things!). Strings are immutable, which means they cannot be changed. But they do have lots of built-in functions that can return a new string (or lots of other things!).
Let's look at an example: Let's look at an example:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s1 = "This is a string" s1 = "This is a string"
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Indexing a string returns the characters of the string: Indexing a string returns the characters of the string:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(s1[0]) print(s1[0])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We can also slice: We can also slice:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(s1[0:6]) print(s1[0:6])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Strings do not allow you to directly change Strings do not allow you to directly change
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Built-in string functions ### Built-in string functions
Strings have a bunch of useful built-in functions: Strings have a bunch of useful built-in functions:
https://docs.python.org/3/library/stdtypes.html#string-methods https://docs.python.org/3/library/stdtypes.html#string-methods
some of which we will look at here: some of which we will look at here:
### Splitting a string ### Splitting a string
Strings have a built-in function `split()`. By default, it will return a list of "words" by using whitespaces as the separator: Strings have a built-in function `split()`. By default, it will return a list of "words" by using whitespaces as the separator:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s1.split() s1.split()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Passing `.` as an argument, `split()` will use that as a separator, which is useful for working with filenames: Passing `.` as an argument, `split()` will use that as a separator, which is useful for working with filenames:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
input_file = 'myfile.dat' input_file = 'myfile.dat'
output_file = input_file.split('.')[0] output_file = input_file.split('.')[0]
output_file += "_processed.dat" output_file += "_processed.dat"
print(output_file) print(output_file)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Replacing parts of strings ### Replacing parts of strings
The function `replace()` replace substrings in your string for you: The function `replace()` replace substrings in your string for you:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s2 = "This is a long sentence. It is a good idea to end it." s2 = "This is a long sentence. It is a good idea to end it."
print(s2) print(s2)
print(s2.replace(" is", " was")) print(s2.replace(" is", " was"))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Note that without the space, it will also replace the "is" in "This": Note that without the space, it will also replace the "is" in "This":
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(s2) print(s2)
print(s2.replace("is", "was")) print(s2.replace("is", "was"))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Testing for the contents of a string ### Testing for the contents of a string
You can check if a substring is found inside a string using the `in` logical operator: You can check if a substring is found inside a string using the `in` logical operator:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
if "this" in "somewhere in this sentence": if "this" in "somewhere in this sentence":
print("We found a 'this'") print("We found a 'this'")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# It is case sensitive: # It is case sensitive:
if "this" in "This is a sentence": if "this" in "This is a sentence":
print("This will not get printed") print("This will not get printed")
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# But you can use the .lower() function of a string to do case insensitive checks # But you can use the .lower() function of a string to do case insensitive checks
s3 = "This is a sentence" s3 = "This is a sentence"
if "this" in s3.lower(): if "this" in s3.lower():
print("Using .lower(), s3 is converted to all lower-case:\n") print("Using .lower(), s3 is converted to all lower-case:\n")
print("s3.lower = '%s'\n" % s3.lower()) print("s3.lower = '%s'\n" % s3.lower())
print("And now we do find the substring 'this'") print("And now we do find the substring 'this'")
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Here, we can also see an example of special characters in strings: a `\n` in a string specifies a "new line": Here, we can also see an example of special characters in strings: a `\n` in a string specifies a "new line":
https://docs.python.org/3/reference/lexical_analysis.html#strings https://docs.python.org/3/reference/lexical_analysis.html#strings
Note that if you want to print a backslash `\`, you need to put a double backslash in your string: `\\`. Note that if you want to print a backslash `\`, you need to put a double backslash in your string: `\\`.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### String formatting ### String formatting
Until now, we have been printing values of our variables using the standard `str()` conversion of numbers to strings: Until now, we have been printing values of our variables using the standard `str()` conversion of numbers to strings:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 11/300 a = 11/300
print("The value of a is", a) print("The value of a is", a)
# The above print() statement is equivalent to: # The above print() statement is equivalent to:
output = "The value of a is" output = "The value of a is"
output += " " output += " "
output += str(a) output += str(a)
print(output) print(output)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
But maybe we don't want so many digits in our text output. Say I want only two digits. How can I do this? But maybe we don't want so many digits in our text output. Say I want only two digits. How can I do this?
For this, python supports "string formatting". My personal preference is to work with traditional "printf-style" formatting, inherited from the C programming language: For this, python supports "string formatting". My personal preference is to work with traditional "printf-style" formatting, inherited from the C programming language:
https://docs.python.org/3/library/stdtypes.html#printf-style-bytes-formatting https://docs.python.org/3/library/stdtypes.html#printf-style-bytes-formatting
It sounds a bit scary at first, but it's actually pretty easy to use. It works by using a special operator `%` that works with strings. It sounds a bit scary at first, but it's actually pretty easy to use. It works by using a special operator `%` that works with strings.
To use it, you include a special text in your string that starts with `%`, followed by a sequence of numbers and letters that you use to tell python how you want the string to be formatted. To use it, you include a special text in your string that starts with `%`, followed by a sequence of numbers and letters that you use to tell python how you want the string to be formatted.
Here are some examples: Here are some examples:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Floating point format with 4 digits # Floating point format with 4 digits
print("The value of a is %.4f" % a) print("The value of a is %.4f" % a)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Exponential notation with two digits # Exponential notation with two digits
print("The value of a is %.2e" % a) print("The value of a is %.2e" % a)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# A string with the formatting not at the end # A string with the formatting not at the end
print("The value of a is %.2e seconds" % a) print("The value of a is %.2e seconds" % a)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Some additional matrix creation routines # Some additional matrix creation routines
There are several functions for making matrices which you may find useful someday: There are several functions for making matrices which you may find useful someday:
https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html
including this one which I use often: including this one which I use often:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# The identity matrix # The identity matrix
print(np.eye(10)) print(np.eye(10))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# A band diagonal matrix # A band diagonal matrix
print(np.eye(10,k=-1)) print(np.eye(10,k=-1))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Mutable objects and "call by reference" ## Mutable objects and "call by reference"
### The `=` operator ### The `=` operator
Now that we have introduced some more advanced data types, it is time to go back and revisit one of our first topics: the `=` opeartor. Now that we have introduced some more advanced data types, it is time to go back and revisit one of our first topics: the `=` opeartor.
At the start of the first notebook, we introduced the **assignment operator** `=`, and saw that it could be used to give new values to a variable based on the value of another variable: At the start of the first notebook, we introduced the **assignment operator** `=`, and saw that it could be used to give new values to a variable based on the value of another variable:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 5 a = 5
b = a b = a
print(b) print(b)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
What happens if we change the value of `a` after the statment `b = a`? For example: What happens if we change the value of `a` after the statment `b = a`? For example:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 5 a = 5
b = a b = a
a = 6 a = 6
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
What value does `b` have? Does it have the value of `5` that `a` had when we performed the assignment operation, or does it have `6` (the new values of `a`)? What value does `b` have? Does it have the value of `5` that `a` had when we performed the assignment operation, or does it have `6` (the new values of `a`)?
The obvious answer would be that `b` should have the answer `5`, right? Let's check it: The obvious answer would be that `b` should have the answer `5`, right? Let's check it:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 5 a = 5
b = a b = a
a = 6 a = 6
print(b) print(b)
``` ```
%% Output
5
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
OK, that seems to make sense. OK, that seems to make sense.
Now let's take a look at and examples with lists. We will create a list `a`, using the assignment operator to make a list variable `b = a`, and then change the values in the list `a`. Now let's take a look at and examples with lists. We will create a list `a`, using the assignment operator to make a list variable `b = a`, and then change the values in the list `a`.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = [2,1] a = [2,1]
b = a b = a
a[0] = 1 a[0] = 1
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now question: did `a[0] = 1` change the value of of `b`? Let's check: Now question: did `a[0] = 1` change the value of of `b`? Let's check:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(b) print(b)
``` ```
%% Output
[1, 1]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Changing the values of `a` also changed list `b` for some reason? **WHY!!!!?????!!! WHAT IS GOING ON?!!?** Changing the values of `a` also changed list `b` for some reason? **WHY!!!!?????!!! WHAT IS GOING ON?!!?**
### "Call by value" and "Call by reference" ### "Call by value" and "Call by reference"
To understand what is going on here, we have to understand how computer programs store variables and their values. To understand what is going on here, we have to understand how computer programs store variables and their values.
When I create a variable `a` in a python by giving it a value `5`, for example, python creates a space in your computers memory where it puts the value `5` and then makes a name for that variable `a` in the kernel's list of variables that points to that spot in memory. When I create a variable `a` in a python by giving it a value `5`, for example, python creates a space in your computers memory where it puts the value `5` and then makes a name for that variable `a` in the kernel's list of variables that points to that spot in memory.
For some types of objects in python, specifically "immutable" ("unchangeable") object types, when you execute the statement `b = a`, python will create a new spot in your computers memory for variable `b`, copy the value `5` into that memory spot, and then makes variable `b` point to this new spot in the kernel's list of variables. For some types of objects in python, specifically "immutable" ("unchangeable") object types, when you execute the statement `b = a`, python will create a new spot in your computers memory for variable `b`, copy the value `5` into that memory spot, and then makes variable `b` point to this new spot in the kernel's list of variables.
This procedure is called "call by value" in programming languages, and is illustrated here: This procedure is called "call by value" in programming languages, and is illustrated here:
<img src="call_by_value.png"></img> <img src="resource/asnlib/public/call_by_value.png"></img>
For "mutable" objects, python uses a different concept: "call by reference". In call by reference, `b = a` instead does the following: it make a new variable `b` in the list of variables, and make it point to the spot in memory where variable `a` is stored, illustrated here: For "mutable" objects, python uses a different concept: "call by reference". In call by reference, `b = a` instead does the following: it make a new variable `b` in the list of variables, and make it point to the spot in memory where variable `a` is stored, illustrated here:
<img src="call_by_reference.png"></img> <img src="resource/asnlib/public/call_by_reference.png"></img>
It is now obvious why changing the values in `a` will also changes the values in `b`: it is because they point to the same data in your computers memory. It is now obvious why changing the values in `a` will also changes the values in `b`: it is because they point to the same data in your computers memory.
"Call by reference" also holds for when you are passing variables to functions: "Call by reference" also holds for when you are passing variables to functions:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def set_first_entry_to_zero(x): def set_first_entry_to_zero(x):
x[0] = 0 x[0] = 0
a = [1,2] a = [1,2]
set_first_entry_to_zero(a) set_first_entry_to_zero(a)
print(a) print(a)
``` ```
%% Output
[0, 2]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We can see that our function changed the value of the variable mylist! This was not possible with integers for example: We can see that our function changed the value of the variable mylist! This was not possible with integers for example:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def set_to_zero(x): def set_to_zero(x):
x = 0 x = 0
a = 1 a = 1
set_to_zero(a) set_to_zero(a)
print(a) print(a)
``` ```
%% Output
1
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Why use "call by reference" at all? I find it confusing! ### Why use "call by reference" at all? I find it confusing!
You might ask: why python does this? Well, one reason is that it is that lists, and in particular numpy arrays that we will look at next, can sometime become very big, taking up 100 MB of memory or more. If python used "call by value" for such big things all the time, it would use up massive amounts of memory! Every function call or assignment statement would accdientally use up another 100 MB of memory! By using "call by reference", it can avoid accidentally filling up your computers memory every time you use the `=` operator. You might ask: why python does this? Well, one reason is that it is that lists, and in particular numpy arrays that we will look at next, can sometime become very big, taking up 100 MB of memory or more. If python used "call by value" for such big things all the time, it would use up massive amounts of memory! Every function call or assignment statement would accdientally use up another 100 MB of memory! By using "call by reference", it can avoid accidentally filling up your computers memory every time you use the `=` operator.
If you really want to have a *copy* of a list (or a numpy array), these objects typically have `copy()` functions built in that return instead a copy of the object, for when you really need one. If you really want to have a *copy* of a list (or a numpy array), these objects typically have `copy()` functions built in that return instead a copy of the object, for when you really need one.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = [2,1] a = [2,1]
b = a.copy() b = a.copy()
print(b) print(b)
a[0] = 1 a[0] = 1
print(b) print(b)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Now, `b` is unaffected by your changes to `a` because the name `b` points to a new copy of the array in memory. Now, `b` is unaffected by your changes to `a` because the name `b` points to a new copy of the array in memory.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Interactive plots with ipywidgets ## Interactive plots with ipywidgets
One of the cool things that is easy to do in Jupter notebooks is to make "interactive" plots. One of the cool things that is easy to do in Jupter notebooks is to make "interactive" plots.
For example, in the projectile example above, I may want to be able to play with the angle and see how this changes my trajectory. For this, there is a very easy to use and convenient library called `ipywidgets`. For example, in the projectile example above, I may want to be able to play with the angle and see how this changes my trajectory. For this, there is a very easy to use and convenient library called `ipywidgets`.
The way it works is we make a function that generates our plot that takes the parameter we want to play with as an argument. We then call an `ipywidgets` function called `interact()`, and it will automatically make a "live update" plot in your web browser in which you can adjust the parameter an see how the plot changes. The way it works is we make a function that generates our plot that takes the parameter we want to play with as an argument. We then call an `ipywidgets` function called `interact()`, and it will automatically make a "live update" plot in your web browser in which you can adjust the parameter an see how the plot changes.
Let's look at an example: Let's look at an example:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from ipywidgets import interact from ipywidgets import interact
v0 = 10 # m/s v0 = 10 # m/s
g = 9.8 # m/s^2 g = 9.8 # m/s^2
# We will allow theta to be adjusted and start it at 45 degrees # We will allow theta to be adjusted and start it at 45 degrees
def update_plot(theta=45): def update_plot(theta=45):
theta *= np.pi/180 # convert to radians theta *= np.pi/180 # convert to radians
y = -g/(2*v0**2*np.cos(theta)**2)*x**2 + x*np.tan(theta) y = -g/(2*v0**2*np.cos(theta)**2)*x**2 + x*np.tan(theta)
plt.plot(x,y) plt.plot(x,y)
plt.ylim(-1,6) # Manually set the ylimits plt.ylim(-1,6) # Manually set the ylimits
plt.xlabel("Distance (m)") plt.xlabel("Distance (m)")
plt.ylabel("Height (m)") plt.ylabel("Height (m)")
plt.axhline(0, ls=":", c="grey") plt.axhline(0, ls=":", c="grey")
plt.show() plt.show()
# Now we call interact, and give it a tuple specifiying the min, max and step for the theta slider # Now we call interact, and give it a tuple specifiying the min, max and step for the theta slider
interact(update_plot, theta=(0,89,2)) interact(update_plot, theta=(0,89,2))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
It is a bit slow in updating if you wiggle it too much with the mouse, but if you click on the slider and adjust it using the arrow keys on your keyboard, it works pretty well. It is a bit slow in updating if you wiggle it too much with the mouse, but if you click on the slider and adjust it using the arrow keys on your keyboard, it works pretty well.
If you are fitting a line to your data, this can also be very useful for getting a good initial guess: If you are fitting a line to your data, this can also be very useful for getting a good initial guess:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def update_plot2(slope=0.5): def update_plot2(slope=0.5):
line = t*slope line = t*slope
plt.plot(t,v, '.') plt.plot(t,v, '.')
plt.plot(t,line, lw=4) plt.plot(t,line, lw=4)
plt.xlabel("Time (s)") plt.xlabel("Time (s)")
plt.ylabel("Voltage (V)") plt.ylabel("Voltage (V)")
plt.show() plt.show()
interact(update_plot2, slope=(0,10,0.1)) interact(update_plot2, slope=(0,10,0.1))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
It is also easy to make two sliders: It is also easy to make two sliders:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def update_plot3(slope=0.5, offset=0): def update_plot3(slope=0.5, offset=0):
line = t*slope+offset line = t*slope+offset
plt.plot(t,v, '.') plt.plot(t,v, '.')
plt.plot(t,line, lw=4) plt.plot(t,line, lw=4)
plt.xlabel("Time (s)") plt.xlabel("Time (s)")
plt.ylabel("Voltage (V)") plt.ylabel("Voltage (V)")
plt.show() plt.show()
interact(update_plot3, slope=(0,10,0.1), offset=(-4,3,0.2)) interact(update_plot3, slope=(0,10,0.1), offset=(-4,3,0.2))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Functions ## Functions
### Keyword and optional arguments ### Keyword and optional arguments
In addition to the "positional" arguments we introduced earlier, python also supports another type of argument: the "keyword" argument. These are often used for "optional" arguments that you don't neccessarily need but may want to give the user the option of using. The syntax is: In addition to the "positional" arguments we introduced earlier, python also supports another type of argument: the "keyword" argument. These are often used for "optional" arguments that you don't neccessarily need but may want to give the user the option of using. The syntax is:
``` ```
def function_name(var1, optional_var2 = default_value) def function_name(var1, optional_var2 = default_value)
... ...
``` ```
The "default_value" is the value that the optional argument will have if it is not specified by the user. The "default_value" is the value that the optional argument will have if it is not specified by the user.
In python-speak, these "optional" arguement as called "keyword" arguments, and the normal arguments we introduced above are called "positional" arguments. In python, in both defining and using functions, keyword arguments must always come after all of the positional arguments. In python-speak, these "optional" arguement as called "keyword" arguments, and the normal arguments we introduced above are called "positional" arguments. In python, in both defining and using functions, keyword arguments must always come after all of the positional arguments.
Here, we will show an example where we use an optional parameter to change the way we print the status sentence. Here, we will show an example where we use an optional parameter to change the way we print the status sentence.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def print_status4(x, long=True): def print_status4(x, long=True):
if long: if long:
print("The value of the first input variable is ", x) print("The value of the first input variable is ", x)
else: else:
print("Val is ", x) print("Val is ", x)
print_status4(1) print_status4(1)
print_status4(2.5, long=True) print_status4(2.5, long=True)
print_status4(2.4, long=False) print_status4(2.4, long=False)
``` ```
%% Output
The value of the first input variable is 1
The value of the first input variable is 2.5
Val is 2.4
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Because python assigns the value of keyword argument variables in the function by matching the keyword and not their position in the list, if you have multiple keyword arguments, you can also change the order of them when you use the function. Because python assigns the value of keyword argument variables in the function by matching the keyword and not their position in the list, if you have multiple keyword arguments, you can also change the order of them when you use the function.
For example, if I define a function: For example, if I define a function:
``` ```
def myfunction(x, var1=1, var2=4): def myfunction(x, var1=1, var2=4):
... ...
``` ```
then both of these would do the same thing: then both of these would do the same thing:
``` ```
myfunction(1,var1=3, var2=54) myfunction(1,var1=3, var2=54)
myfunction(1,var2=54, var2=3) myfunction(1,var2=54, var2=3)
``` ```
Finally, one can also use keywords as a way to send values to functions even if the functions are not defined with keyword arguments. This allows you to change to order of variables you send to a function if you want. For example: Finally, one can also use keywords as a way to send values to functions even if the functions are not defined with keyword arguments. This allows you to change to order of variables you send to a function if you want. For example:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def myfun(x,y): def myfun(x,y):
print("x is", x) print("x is", x)
print("y is", y) print("y is", y)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
myfun(1,2) myfun(1,2)
``` ```
%% Output
x is 1
y is 2
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
myfun(2,1) myfun(2,1)
``` ```
%% Output
x is 2
y is 1
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
myfun(x=1,y=2) myfun(x=1,y=2)
``` ```
%% Output
x is 1
y is 2
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
myfun(y=2,x=1) myfun(y=2,x=1)
``` ```
%% Output
x is 1
y is 2
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Python Error Messages with functions ### Python Error Messages with functions
In the first notebook, we learned some of the basics of how to understand python errors. In the first notebook, we learned some of the basics of how to understand python errors.
Sometimes, though, if you are using functions from a library, the error messages can get very long, and trickier to understand. Sometimes, though, if you are using functions from a library, the error messages can get very long, and trickier to understand.
Here, we will look at how to dissect an example of a more complicated error you can get from a function in a library and how to figure out where the useful information is. Here, we will look at how to dissect an example of a more complicated error you can get from a function in a library and how to figure out where the useful information is.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
plt.plot([1,2], [1,2,3]) plt.plot([1,2], [1,2,3])
``` ```
%% Output
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-11-19f47447b05c> in <module>()
1 import matplotlib.pyplot as plt
----> 2 plt.plot([1,2], [1,2,3])
C:\Programs\Anaconda3\lib\site-packages\matplotlib\pyplot.py in plot(*args, **kwargs)
3356 mplDeprecation)
3357 try:
-> 3358 ret = ax.plot(*args, **kwargs)
3359 finally:
3360 ax._hold = washold
C:\Programs\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1853 "the Matplotlib list!)" % (label_namer, func.__name__),
1854 RuntimeWarning, stacklevel=2)
-> 1855 return func(ax, *args, **kwargs)
1856
1857 inner.__doc__ = _add_data_doc(inner.__doc__,
C:\Programs\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, *args, **kwargs)
1525 kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
1526
-> 1527 for line in self._get_lines(*args, **kwargs):
1528 self.add_line(line)
1529 lines.append(line)
C:\Programs\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _grab_next_args(self, *args, **kwargs)
404 this += args[0],
405 args = args[1:]
--> 406 for seg in self._plot_args(this, kwargs):
407 yield seg
408
C:\Programs\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
381 x, y = index_of(tup[-1])
382
--> 383 x, y = self._xy_from_xy(x, y)
384
385 if self.command == 'plot':
C:\Programs\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _xy_from_xy(self, x, y)
240 if x.shape[0] != y.shape[0]:
241 raise ValueError("x and y must have same first dimension, but "
--> 242 "have shapes {} and {}".format(x.shape, y.shape))
243 if x.ndim > 2 or y.ndim > 2:
244 raise ValueError("x and y can be no greater than 2-D, but have "
ValueError: x and y must have same first dimension, but have shapes (2,) and (3,)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Wow, that was a really big error message. What do I do with all of this? Wow, that was a really big error message. What do I do with all of this?
The most important information is at the very top and at the very bottom (you can just skip the rest for now...). The most important information is at the very top and at the very bottom (you can just skip the rest for now...).
At the top, it shows us the part of our code that triggered the error: At the top, it shows us the part of our code that triggered the error:
<img src="big_error_1.png"></img> <img src="resource/asnlib/public/big_error_1.png"></img>
The error type is a `ValueError`, which according to the documentation, indicates "an argument that has the right type but an inappropriate value". The error type is a `ValueError`, which according to the documentation, indicates "an argument that has the right type but an inappropriate value".
In the middle there is then a whole bunch of stuff we won't easily understand. What is all of this? This is showing us what is happening inside all the functions of the matplotlib library...probably unless you are a bit of an expert, you will not really understand all of this. In the middle there is then a whole bunch of stuff we won't easily understand. What is all of this? This is showing us what is happening inside all the functions of the matplotlib library...probably unless you are a bit of an expert, you will not really understand all of this.
We can learn more, though, by looking at the last line: We can learn more, though, by looking at the last line:
<img src="big_error_2.png"></img> <img src="big_error_2.png"></img>
What are `x` and `y`? They are the variable names in the library function in matplotlib where we ended up, so probably also maybe not immediately obvious what they are. But we can see more about the problem: it is complaining that two of the variables do not have the same shape. What are `x` and `y`? They are the variable names in the library function in matplotlib where we ended up, so probably also maybe not immediately obvious what they are. But we can see more about the problem: it is complaining that two of the variables do not have the same shape.
If we look up at the line in our code that triggered the error, we can see that we have supplied two arguments that have a different number of elements: `plt.plot([1,2], [1,2,3])` If we look up at the line in our code that triggered the error, we can see that we have supplied two arguments that have a different number of elements: `plt.plot([1,2], [1,2,3])`
It would seem that both the first and second variables of the `plot` function should have the same number of elements. Indeed, if we try: It would seem that both the first and second variables of the `plot` function should have the same number of elements. Indeed, if we try:
`plt.plot([1,2,3], [1,2,3,])` `plt.plot([1,2,3], [1,2,3,])`
then the error goes away: then the error goes away:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
plt.plot([1,2,3], [1,2,3,]) plt.plot([1,2,3], [1,2,3,])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Learning objectives list ## Learning objectives list
Not crucial since this notebook is optional, but maybe useful to have. Not crucial since this notebook is optional, but maybe useful to have.
**Learning objectives for this notebook:** **Learning objectives for this notebook:**
* Student is able to create and index tuples and lists by hand and using the `range()` operator * Student is able to create and index tuples and lists by hand and using the `range()` operator
* Student is able to loop over tuples and lists without indexing * Student is able to loop over tuples and lists without indexing
* Student is able to extract subsets of lists and tuples using slicing * Student is able to extract subsets of lists and tuples using slicing
* Student is able to change individual entries of a list using indexing and the assignment operator * Student is able to change individual entries of a list using indexing and the assignment operator
* Student is able to use built-in functions of lists * Student is able to use built-in functions of lists
* Student is able to use indexing to extract substrings from a string * Student is able to use indexing to extract substrings from a string
* Student is able to use built-in string functions * Student is able to use built-in string functions
* Student is able to split a string into a list of strings using the `.split()` function * Student is able to split a string into a list of strings using the `.split()` function
* Student is able to search in strings using the `in` operator * Student is able to search in strings using the `in` operator
* Student is able to use formating and the `%` opereator to control how variables are translated into strings * Student is able to use formating and the `%` opereator to control how variables are translated into strings
* Student is able to predict how variables behave differently for "mutable" and "non-mutable" objects (call-by-value vs. call-by-reference) * Student is able to predict how variables behave differently for "mutable" and "non-mutable" objects (call-by-value vs. call-by-reference)
* Student is able to use the `ipywidgets` `interact()` function to explore functions using sliders * Student is able to use the `ipywidgets` `interact()` function to explore functions using sliders
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
Additional Material/resource/asnlib/public/call_by_reference.png

11.8 KiB

Additional Material/resource/asnlib/public/call_by_value.png

11.9 KiB

Course_Information/Course_Information_anaconda_prompt_windows.png

25.2 KiB

Course_Information/Course_Information_cell_type.png

20.8 KiB

Course_Information/Course_Information_disable_box.png

17.3 KiB

Course_Information/Course_Information_enable_toc.png

14.5 KiB

Course_Information/Course_Information_mac_terminal.png

123 KiB

Course_Information/Course_Information_nbextensions.png

12.2 KiB

Course_Information/Course_Information_notebook_server.png

228 KiB

%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Installing and running the server ## Installing and running the server
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### My Jupyter server has crashed, link does not work ### My Jupyter server has crashed, link does not work
If the link http://localhost:8888 does not work, your server may have crashed (or may be running on a different port if you accidentally started muliple servers). If the link http://localhost:8888 does not work, your server may have crashed (or may be running on a different port if you accidentally started muliple servers).
If this is the case, you should go back to the Anaconda prompt window it was running in and do the following: If this is the case, you should go back to the Anaconda prompt window it was running in and do the following:
1. Type `Ctrl-C` 1. Type `Ctrl-C`
2. Run the command `jupyter notebook stop` 2. Run the command `jupyter notebook stop`
3. Run the command `jupyter notebook start` 3. Run the command `jupyter notebook start`
If you cannot find the Anaconda prompt window anymore, you can also open a new Anaconda prompt window and do steps 2 and 3 above. If you cannot find the Anaconda prompt window anymore, you can also open a new Anaconda prompt window and do steps 2 and 3 above.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### My files are not in my home directory, how do I get to them? ### My files are not in my home directory, how do I get to them?
If your files are stored outside of your home directory, for example if they are on your D: drive in windows, you will have to first change directories in the Anaconda prompt to that folder before you run the command `jupyter notebook`. If your files are stored outside of your home directory, for example if they are on your D: drive in windows, you will have to first change directories in the Anaconda prompt to that folder before you run the command `jupyter notebook`.
For example, let's say your files are on the D: drive in a folder `D:\Python\Practicum`. First you should stop the notebook server (see steps 1 and 2 of "Restarting a notebook server") and then you can use the following commands in the Anaconda prompt: For example, let's say your files are on the D: drive in a folder `D:\Python\Practicum`. First you should stop the notebook server (see steps 1 and 2 of "Restarting a notebook server") and then you can use the following commands in the Anaconda prompt:
* `d:` * `d:`
* `cd Python` * `cd Python`
* `jupyter notebook` * `jupyter notebook`
This will start a notebook server with the "root directory" as `D:\Python`, which will allow you to access all the files in subfolders of `D:\Python`. This will start a notebook server with the "root directory" as `D:\Python`, which will allow you to access all the files in subfolders of `D:\Python`.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Why is my web browser going to http://localhost:8889/ (instead of 8888)? ### Why is my web browser going to http://localhost:8889/ (instead of 8888)?
This can happen when you (accidentally) open multiple notebook servers. You can list all the notebook servers that are running using the following command at the Anaconda prompt: This can happen when you (accidentally) open multiple notebook servers. You can list all the notebook servers that are running using the following command at the Anaconda prompt:
`jupyter notebook list` `jupyter notebook list`
You can then close any extra ones you don't want by using the `stop` command with their "port" number (the four numbers after "localhost"). For example, to stop one running on port 8889, use: You can then close any extra ones you don't want by using the `stop` command with their "port" number (the four numbers after "localhost"). For example, to stop one running on port 8889, use:
`jupyter notebook stop 8889` `jupyter notebook stop 8889`
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Using Jupyter Notebooks ## Using Jupyter Notebooks
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### My code cell sometimes changes to a text cell, how do we change this back? ### My code cell sometimes changes to a text cell, how do we change this back?
You have probably changed the "cell type" from "Code" to "Markdown". You can change it back using the menu toolbar dropdown box: You have probably changed the "cell type" from "Code" to "Markdown". You can change it back using the menu toolbar dropdown box:
<img src="cell_type.png"></img> <img src="resource/asnlib/public/Course_Information_cell_type.png"></img>
There also <a href=https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Notebook%20Basics.html#Keyboard-Navigation>keyboard shortcuts</a> for many things. There also <a href=https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Notebook%20Basics.html#Keyboard-Navigation>keyboard shortcuts</a> for many things.
Most likely, you pushing the `M` key while the cell was selected in "command" mode (blue border). You can change it back by pushing the `Y` key. Most likely, you pushing the `M` key while the cell was selected in "command" mode (blue border). You can change it back by pushing the `Y` key.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Installation instructions # Installation instructions
This page explains how to: This page explains how to:
1. Install python using Anaconda 1. Install python using Anaconda
2. Install `nbextensions` 2. Install `nbextensions`
3. Start a Jupyter Notebook server 3. Start a Jupyter Notebook server
4. Enable the "Table of Contents" Extension 4. Enable the "Table of Contents" Extension
## 1. Install python using Anaconda ## 1. Install python using Anaconda
First, download and install Anaconda: First, download and install Anaconda:
https://www.anaconda.com/distribution/ https://www.anaconda.com/distribution/
Run the installer with the default options. Run the installer with the default options.
**Warning:** Even if you already have Anaconda installed, we recommend that you download it again and re-install it to make sure you have the latest version of the packages. **Warning:** Even if you already have Anaconda installed, we recommend that you download it again and re-install it to make sure you have the latest version of the packages.
## 2. Install the notebook extensions ## 2. Install the notebook extensions
On **Windows**, open an "Anaconda prompt" (type "Anaconda prompt" in search in Windows 10, or look for it in the program menu): On **Windows**, open an "Anaconda prompt" (type "Anaconda prompt" in search in Windows 10, or look for it in the program menu):
<img src="anaconda_prompt_windows.png" width=50%></img> <img src="resource/asnlib/public/Course_Information_anaconda_prompt_windows.png" width=40%></img>
On **MacOS**, open a "Teminal" app (use "Spotlight Search" and type "Terminal"): On **MacOS**, open a "Teminal" app (use "Spotlight Search" and type "Terminal"):
<img src="mac_terminal.png" width=40%></img> <img src="resource/asnlib/public/Course_Information_mac_terminal.png" width=40%></img>
At the command line of the terminal, run the following command by copy-pasting in the text and typing "enter": At the command line of the terminal, run the following command by copy-pasting in the text and typing "enter":
`conda install -c conda-forge jupyter_contrib_nbextensions` `conda install -c conda-forge jupyter_contrib_nbextensions`
When it is done, you can close the terminal, or you can leave it open for the next step. When it is done, you can close the terminal, or you can leave it open for the next step.
## 3. Start a jupyter notebook server ## 3. Start a jupyter notebook server
From the "Anaconda prompt" (in windows) or from "Terminal" (on MacOS), run the following command: From the "Anaconda prompt" (in windows) or from "Terminal" (on MacOS), run the following command:
`jupyter notebook` `jupyter notebook`
This will start the notebook server and automatically open a tab in your web browser sending you to the (local) web address of the notebook server running on your computer, showing you the files in your home directory: This will start the notebook server and automatically open a tab in your web browser sending you to the (local) web address of the notebook server running on your computer, showing you the files in your home directory:
<img width=70% src="notebook_server.png"><img> <img width=70% src="resource/asnlib/public/Course_Information_notebook_server.png"><img>
If you close your browser, you can always use this link to get back to your local notebook server: If you close your browser, you can always use this link to get back to your local notebook server:
http://localhost:8888/ http://localhost:8888/
You should leave the terminal running and minimize the window. You should leave the terminal running and minimize the window.
## 4. Enable the "Table of Contents" notebook extension ## 4. Enable the "Table of Contents" notebook extension
The notebooks for the Python Practicum course use the "Table of contents" notebook extension to make enable section numbers and tables of contents. (The notebooks will work fine without them, but you will miss the table of contents button in the toolbar and you will miss the section numbering.) The notebooks for the Python Practicum course use the "Table of contents" notebook extension to make enable section numbers and tables of contents. (The notebooks will work fine without them, but you will miss the table of contents button in the toolbar and you will miss the section numbering.)
To enable it, go to the notebook server home page: To enable it, go to the notebook server home page:
http://localhost:8888/ http://localhost:8888/
Click on the "Nbextensions" tab: Click on the "Nbextensions" tab:
<img src="nbextensions.png" width=50%></img> <img src="resource/asnlib/public/Course_Information_nbextensions.png" width=50%></img>
Make sure that this box is not clicked: Make sure that this box is not clicked:
<img src="disable_box.png" width=50%></img> <img src="resource/asnlib/public/Course_Information_disable_box.png" width=50%></img>
<p> And enable the "Table of Contents" extension: <p> And enable the "Table of Contents" extension:
<img src="enable_toc.png" width=50%></img> <img src="resource/asnlib/public/Course_Information_enable_toc.png" width=50%></img>
## Frequently asked questions ## Frequently asked questions
### My Jupyter server has crashed, link does not work ### My Jupyter server has crashed, link does not work
If the link http://localhost:8888 does not work, your server may have crashed (or may be running on a different port if you accidentally started muliple servers). If the link http://localhost:8888 does not work, your server may have crashed (or may be running on a different port if you accidentally started muliple servers).
If this is the case, you should go back to the Anaconda prompt window it was running in and do the following: If this is the case, you should go back to the Anaconda prompt window it was running in and do the following:
1. Type `Ctrl-C` 1. Type `Ctrl-C`
2. Run the command `jupyter notebook stop` 2. Run the command `jupyter notebook stop`
3. Run the command `jupyter notebook start` 3. Run the command `jupyter notebook start`
If you cannot find the Anaconda prompt window anymore, you can also open a new Anaconda prompt window and do steps 2 and 3 above. If you cannot find the Anaconda prompt window anymore, you can also open a new Anaconda prompt window and do steps 2 and 3 above.
### My files are not in my home directory, how do I get to them? ### My files are not in my home directory, how do I get to them?
If your files are stored outside of your home directory, for example if they are on your D: drive in windows, you will have to first change directories in the Anaconda prompt to that folder before you run the command `jupyter notebook`. If your files are stored outside of your home directory, for example if they are on your D: drive in windows, you will have to first change directories in the Anaconda prompt to that folder before you run the command `jupyter notebook`.
For example, let's say your files are on the D: drive in a folder `D:\Python\Practicum`. First you should stop the notebook server (see steps 1 and 2 of "Restarting a notebook server") and then you can use the following commands in the Anaconda prompt: For example, let's say your files are on the D: drive in a folder `D:\Python\Practicum`. First you should stop the notebook server (see steps 1 and 2 of "Restarting a notebook server") and then you can use the following commands in the Anaconda prompt:
* `d:` * `d:`
* `cd Python` * `cd Python`
* `jupyter notebook` * `jupyter notebook`
This will start a notebook server with the "root directory" as `D:\Python`, which will allow you to access all the files in subfolders of `D:\Python`. This will start a notebook server with the "root directory" as `D:\Python`, which will allow you to access all the files in subfolders of `D:\Python`.
### Why is my web browser going to http://localhost:8889/ (instead of 8888)? ### Why is my web browser going to http://localhost:8889/ (instead of 8888)?
This can happen when you (accidentally) open multiple notebook servers. You can list all the notebook servers that are running using the following command at the Anaconda prompt: This can happen when you (accidentally) open multiple notebook servers. You can list all the notebook servers that are running using the following command at the Anaconda prompt:
`jupyter notebook list` `jupyter notebook list`
You can then close any extra ones you don't want by using the `stop` command with their "port" number (the four numbers after "localhost"). For example, to stop one running on port 8889, use: You can then close any extra ones you don't want by using the `stop` command with their "port" number (the four numbers after "localhost"). For example, to stop one running on port 8889, use:
`jupyter notebook stop 8889` `jupyter notebook stop 8889`
......
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Python in the practicum # Python in the practicum
## Overview ## Overview
As part of the "Inleidend Practicum" course, you will have 5 lectures in which we will teach you the basics of programming with python. As part of the "Inleidend Practicum" course, you will have 5 lectures in which we will teach you the basics of programming with python.
For doing this, we have created a set of 5 "Lecture Notebooks", with the topics: For doing this, we have created a set of 5 "Lecture Notebooks", with the topics:
* **Notebook 1: Python Basics** * **Notebook 1: Python Basics**
* **Notebook 2: Functions** * **Notebook 2: Functions**
* **Notebook 3: Program Flow Control** * **Notebook 3: Program Flow Control**
* **Notebook 4: Scientific Computing with Numpy** * **Notebook 4: Scientific Computing with Numpy**
* **Notebook 5: Data in Python** * **Notebook 5: Data in Python**
For the material of Notebooks 1-3, we have an assignment connected to each notebook, and for Notebooks 4 and 5, there will be a final project that will cover the material in those notebooks: There are also to additional notebooks: one with advice on good coding practices, and one on "Advanced programming concepts" for those that are interested:
* **Assignment 1 (Must pass)** * **Good coding practices**
* **Assignment 2 (Must pass)** * **Advanced programming concepts**
* **Assignment 3 (Must pass)**
* **Final Project (100%)**
The assignments will be checked in class. You must have completed and passed the three assignments in order to be allowed to submit your final project. **Good coding practices** is a short notebook that you should read and apply in your assignments. **Advanced programming concepts** is optional in this course.
For the material of Notebooks 1-3, we have an assignment connected to each notebook, and for Notebooks 4 and 5, there will be a final project applying what you have learned to data analysis. The python component of this course makes up 15% of your final grade. Each of the assignments will count for 3 points out of 15 towards your python grade component, and the final project will count for 6 points of 15.
* **Assignment 1 (3 points)** Due date: Tuesday, 8 Sep at 17.59
* **Assignment 2 (3 points)** Due date: Tuesday, 15 Sep at 17.59
* **Assignment 3 (3 points)** Due date: Tuesday, 22 Sep at 17.59
* **Final Project (6 points)** Due date: Friday, 25 Sep at 17.59
The assignments must be submitted before the assigned deadlines by using the "Submit" button in Vocareum.
## Platform
You will be working in an online cloud-based computing platform called "Vocareum". You will access Vocareum through the links that will be created in the brightspace course page.
There will be information available in the course MS Teams "Python" channel about how to use Vocareum.
## Pace ## Pace
While there are 5 lectures and 5 notebooks, we encourage you to work at your own pace through the material. More experienced programmers may cover the material more quickly, perhaps with more than one notebook worth of material per lecture, while those with less (or no) programming experience may want to go through the material more slowly and finish the material at home. While there are 5 lectures and 5 notebooks, we encourage you to work at your own pace through the material. More experienced programmers may cover the material more quickly, perhaps with more than one notebook worth of material per lecture, while those with less (or no) programming experience may want to go through the material more slowly and finish the material at home.
## Final Grade You should make sure, however, that you cover the material at a sufficient pace that you do not miss the deadlines for the assignments.
Your python grade will count for 18% of the practicum grade (1ECTS). You grade will be determined by the final project, but your project will only be graded if you have passed all three assignments, which must be checked by a TA or lecturer in the lecture sessions (more on this below).
## What do I do with the "Lecture" notebooks? ## What do I do with the "Lecture" notebooks?
The lecture notebooks explain the concepts of the material we expect you to learn. They contain both "information" sections for you to read, as well as "code sections" that you can run to demonstrate these concepts live. The lecture notebooks explain the concepts of the material we expect you to learn. They contain both "information" sections for you to read, as well as "code sections" that you can run to demonstrate these concepts live.
At the top of each notebook, we have created a summary of the learning objectives we aim to achieve. At the top of each notebook, we have created a summary of the learning objectives we aim to achieve.
What should I do? You should first take a look at the learning objectives at the top of the notebook to understand what we want to achieve, then you can read through the learning material and execute the code cells to see what happens. What should I do? You should first take a look at the learning objectives at the top of the notebook to understand what we want to achieve, then you can read through the learning material and execute the code cells to see what happens.
The notebooks also contain exercises where you can test what you have learned. Some are easy, some are a bit trickier: if you get stuck with the exercises, you should not hesitate to ask a fellow student, a TA, or a lecturer for help. The notebooks also contain exercises where you can test what you have learned. Some are easy, some are a bit trickier: if you get stuck with the exercises, you should not hesitate to ask a fellow student, a TA, or a lecturer for help.
Try it yourself! Feel free to add code cells to the notebook (using the "Insert" menu) to try things out. If you find something you don't understand, you are always welcome to ask a TA or a lecturer to have a look. Try it yourself! Feel free to add code cells to the notebook (using the "Insert" menu) to try things out. If you find something you don't understand, you are always welcome to ask a TA or a lecturer to have a look.
## Assignment Notebooks ## Assignments
For lectures 1-3, there are "Assignment Notebooks" which we will ask you to complete. For lectures 1-3, there are "Assignment Notebooks" which we will ask you to complete.
The Assignment notebooks are designed to test if you have learned and understood the material from the lecture notebooks and have achieved the learning objective we have defined. Once you think you have mastered the material of the lecture notebooks and have played with writing code in the Try it yourself code cells and the exercise cells, you should move on to the Assignment Notebooks. The Assignment notebooks are designed to test if you have learned and understood the material from the lecture notebooks and have achieved the learning objective we have defined. Once you think you have mastered the material of the lecture notebooks and have played with writing code in the Try it yourself code cells and the exercise cells, you should move on to the Assignment Notebooks.
For the assignment notebooks, you should write your answer in the provided cells. When you think you have the correct answers, bring your laptop to a TA or lecturer and have them check your code. If you code is correct and you can explain it properly, then the TA will approve your completion of that assignment and you be marked as a "Pass". Your assignments will be submitted via Vocareum, and **must be submitted before the submission deadline**. In the week of October 5th, there will be short 10 minute examinations with the teaching assistants to determine your grade. In this examination, you will sit with a TA for 5 minutes, quickly demonstrate your code, and explain what the code does. The TA will then take 5 minutes on their own to assess the following criteria:
Our pass criteria are:
* The code achieves what is asked in the question * The code achieves what is asked in the question
* The student is able to explain what the code is doing to the TA * The student is able to explain what the code is doing to the TA
* The code cells contains comments explaining what it is doing * The code cells contains comments explaining what it is doing
If the TA determines that your assignment has not satisfied these criteria, then you can continue to work on it and have it checked again when you think it is correct. A more detailed rubric for the assessment of assignments 1-3 will be made public when ready.
Before the TA marks your assignment as a "Pass", you will be required to upload that code to the appropriate assignment folder on Brightspace.
The assignments must be checked and approved by a TA before the following deadlines:
* Assignment 1: End of session P3
* Assignment 2: End of session P4
* Assignment 3: End of session P5
Individual exceptions are possible for reasons such as illness in discussion with the lecturers.
### Am I allowed to ask for help? ### Am I allowed to ask for help?
Yes, of course! You are welcome to ask the teacher, the TAs, and other students for help with both the material in the Lecture Notebooks and in the Assignment Notebooks. Yes, of course! You are welcome to ask the teacher, the TAs, and other students for help with both the material in the Lecture Notebooks and in the Assignment Notebooks.
Note that the TAs will be happy to help you "debug" your code and point you in the right direction, they will not give you the answers to the assignment questions. Note that the TAs will be happy to help you "debug" your code and point you in the right direction, they will not give you the answers to the assignment questions.
### Am I allowed to copy my friends code? ### Am I allowed to copy my friends code?
No! While we encourage you to ask fellow students for help, you are not allowed to directly cut-and-paste they code (or copy their notebook files). At the end of the course, we will be performing a specialized plagiarism scan (designed for computer code) on the submitted assignments and any anomalies will be investigated. No! While we encourage you to ask fellow students for help, you are not allowed to directly cut-and-paste they code (or copy their notebook files). At the end of the course, we will be performing a specialized plagiarism scan (designed for computer code) on the submitted assignments and any anomalies will be investigated.
## Final Project ## Python Final Project
In addition to the assignments related to the core programming concepts, we will also have a final assignment that will determining your the final grade.
In this final assignment, you will load, process, plot and analyze a dataset using python. You will create a lab-report-style notebook in which you summarize your findings and you will submit this via Brightspace for grading by the TAs.
The final projects will be submitted via Brightspace in an assignment folder with a deadline announced per student group.
**Important:** Your final project will NOT be graded unless you have achieved a pass evaluation on all the assignments as described above.
%% Cell type:code id: tags:
``` python In addition to the assignments related to the core programming concepts, we will also have a final assignment that will be connected to the material of Lecture Notebooks 4 and 5 in which you will apply your python skills for loading, plotting, and analysing data. More information on the format and assessment of the Python Final Project will follow soon.
```
......
...@@ -5,14 +5,15 @@ jupyter: ...@@ -5,14 +5,15 @@ jupyter:
text_representation: text_representation:
extension: .md extension: .md
format_name: markdown format_name: markdown
format_version: '1.1' format_version: '1.2'
jupytext_version: 1.2.2 jupytext_version: 1.3.0
kernelspec: kernelspec:
display_name: Python 3 display_name: Python 3
language: python language: python
name: python3 name: python3
--- ---
<!-- #region -->
# Python in the practicum # Python in the practicum
## Overview ## Overview
...@@ -27,22 +28,34 @@ For doing this, we have created a set of 5 "Lecture Notebooks", with the topics: ...@@ -27,22 +28,34 @@ For doing this, we have created a set of 5 "Lecture Notebooks", with the topics:
* **Notebook 4: Scientific Computing with Numpy** * **Notebook 4: Scientific Computing with Numpy**
* **Notebook 5: Data in Python** * **Notebook 5: Data in Python**
For the material of Notebooks 1-3, we have an assignment connected to each notebook, and for Notebooks 4 and 5, there will be a final project that will cover the material in those notebooks: There are also to additional notebooks: one with advice on good coding practices, and one on "Advanced programming concepts" for those that are interested:
* **Assignment 1 (Must pass)** * **Good coding practices**
* **Assignment 2 (Must pass)** * **Advanced programming concepts**
* **Assignment 3 (Must pass)**
* **Final Project (100%)**
The assignments will be checked in class. You must have completed and passed the three assignments in order to be allowed to submit your final project. **Good coding practices** is a short notebook that you should read and apply in your assignments. **Advanced programming concepts** is optional in this course.
For the material of Notebooks 1-3, we have an assignment connected to each notebook, and for Notebooks 4 and 5, there will be a final project applying what you have learned to data analysis. The python component of this course makes up 15% of your final grade. Each of the assignments will count for 3 points out of 15 towards your python grade component, and the final project will count for 6 points of 15.
* **Assignment 1 (3 points)** Due date: Tuesday, 8 Sep at 17.59
* **Assignment 2 (3 points)** Due date: Tuesday, 15 Sep at 17.59
* **Assignment 3 (3 points)** Due date: Tuesday, 22 Sep at 17.59
* **Final Project (6 points)** Due date: Friday, 25 Sep at 17.59
The assignments must be submitted before the assigned deadlines by using the "Submit" button in Vocareum.
## Platform
You will be working in an online cloud-based computing platform called "Vocareum". You will access Vocareum through the links that will be created in the brightspace course page.
There will be information available in the course MS Teams "Python" channel about how to use Vocareum.
## Pace ## Pace
While there are 5 lectures and 5 notebooks, we encourage you to work at your own pace through the material. More experienced programmers may cover the material more quickly, perhaps with more than one notebook worth of material per lecture, while those with less (or no) programming experience may want to go through the material more slowly and finish the material at home. While there are 5 lectures and 5 notebooks, we encourage you to work at your own pace through the material. More experienced programmers may cover the material more quickly, perhaps with more than one notebook worth of material per lecture, while those with less (or no) programming experience may want to go through the material more slowly and finish the material at home.
## Final Grade You should make sure, however, that you cover the material at a sufficient pace that you do not miss the deadlines for the assignments.
Your python grade will count for 18% of the practicum grade (1ECTS). You grade will be determined by the final project, but your project will only be graded if you have passed all three assignments, which must be checked by a TA or lecturer in the lecture sessions (more on this below).
## What do I do with the "Lecture" notebooks? ## What do I do with the "Lecture" notebooks?
...@@ -56,31 +69,19 @@ The notebooks also contain exercises where you can test what you have learned. S ...@@ -56,31 +69,19 @@ The notebooks also contain exercises where you can test what you have learned. S
Try it yourself! Feel free to add code cells to the notebook (using the "Insert" menu) to try things out. If you find something you don't understand, you are always welcome to ask a TA or a lecturer to have a look. Try it yourself! Feel free to add code cells to the notebook (using the "Insert" menu) to try things out. If you find something you don't understand, you are always welcome to ask a TA or a lecturer to have a look.
## Assignment Notebooks ## Assignments
For lectures 1-3, there are "Assignment Notebooks" which we will ask you to complete. For lectures 1-3, there are "Assignment Notebooks" which we will ask you to complete.
The Assignment notebooks are designed to test if you have learned and understood the material from the lecture notebooks and have achieved the learning objective we have defined. Once you think you have mastered the material of the lecture notebooks and have played with writing code in the Try it yourself code cells and the exercise cells, you should move on to the Assignment Notebooks. The Assignment notebooks are designed to test if you have learned and understood the material from the lecture notebooks and have achieved the learning objective we have defined. Once you think you have mastered the material of the lecture notebooks and have played with writing code in the Try it yourself code cells and the exercise cells, you should move on to the Assignment Notebooks.
For the assignment notebooks, you should write your answer in the provided cells. When you think you have the correct answers, bring your laptop to a TA or lecturer and have them check your code. If you code is correct and you can explain it properly, then the TA will approve your completion of that assignment and you be marked as a "Pass". Your assignments will be submitted via Vocareum, and **must be submitted before the submission deadline**. In the week of October 5th, there will be short 10 minute examinations with the teaching assistants to determine your grade. In this examination, you will sit with a TA for 5 minutes, quickly demonstrate your code, and explain what the code does. The TA will then take 5 minutes on their own to assess the following criteria:
Our pass criteria are:
* The code achieves what is asked in the question * The code achieves what is asked in the question
* The student is able to explain what the code is doing to the TA * The student is able to explain what the code is doing to the TA
* The code cells contains comments explaining what it is doing * The code cells contains comments explaining what it is doing
If the TA determines that your assignment has not satisfied these criteria, then you can continue to work on it and have it checked again when you think it is correct. A more detailed rubric for the assessment of assignments 1-3 will be made public when ready.
Before the TA marks your assignment as a "Pass", you will be required to upload that code to the appropriate assignment folder on Brightspace.
The assignments must be checked and approved by a TA before the following deadlines:
* Assignment 1: End of session P3
* Assignment 2: End of session P4
* Assignment 3: End of session P5
Individual exceptions are possible for reasons such as illness in discussion with the lecturers.
### Am I allowed to ask for help? ### Am I allowed to ask for help?
...@@ -92,16 +93,7 @@ Note that the TAs will be happy to help you "debug" your code and point you in ...@@ -92,16 +93,7 @@ Note that the TAs will be happy to help you "debug" your code and point you in
No! While we encourage you to ask fellow students for help, you are not allowed to directly cut-and-paste they code (or copy their notebook files). At the end of the course, we will be performing a specialized plagiarism scan (designed for computer code) on the submitted assignments and any anomalies will be investigated. No! While we encourage you to ask fellow students for help, you are not allowed to directly cut-and-paste they code (or copy their notebook files). At the end of the course, we will be performing a specialized plagiarism scan (designed for computer code) on the submitted assignments and any anomalies will be investigated.
## Final Project ## Python Final Project
In addition to the assignments related to the core programming concepts, we will also have a final assignment that will determining your the final grade.
In this final assignment, you will load, process, plot and analyze a dataset using python. You will create a lab-report-style notebook in which you summarize your findings and you will submit this via Brightspace for grading by the TAs.
The final projects will be submitted via Brightspace in an assignment folder with a deadline announced per student group.
**Important:** Your final project will NOT be graded unless you have achieved a pass evaluation on all the assignments as described above.
```python
``` In addition to the assignments related to the core programming concepts, we will also have a final assignment that will be connected to the material of Lecture Notebooks 4 and 5 in which you will apply your python skills for loading, plotting, and analysing data. More information on the format and assessment of the Python Final Project will follow soon.
<!-- #endregion -->
%% Cell type:markdown id: tags:
# The Python Online Classroom in TN1405-P 2020/2021
Due to the circumstances, the course in the 2020/2021 academic year will be run primarily online. Fortunately there are many great tools that will enable you to learn online, work online, and intearct with us and each other online. Particularly for programming, this can be very effective.
For the python, there are three important online tools which we will use in the following way:
* **Brightspace / Vocareum:** Where you log in and work
* **Microsoft Teams:** A "virtual classroom"
* **Support Forum:** Where you can post questions both inside and outside of lecture hours
In the sections below, I will describe in a bit more detail how we will use them.
## Brightspace / Vocareum
This is where you we will post information and the material for you to work on. Vocareum is our cloud-based computing platform, and is accessed by links from inside Brightspace.
## Microsoft Teams
We will use Microsoft teams as an online classroom where you can work and interact with the teachers, the TAs, and with each other.
Microsoft teams is a "chat" based communications tool that organises discussions inside a "team" into "channels", similar to the platform discord (https://discord.com/) that some of you may be familiar with from online gaming communities.
For Python, the following channels are relevant:
* **Python:** Where I will post things like instructional videos and other information that is hard to post on brightsapce
* **Tafel 01-10:** Virtual "tables" where you can work with other students using text chat, video chat, posting images / screenshots, and sharing documents
* **TA gevraagd:** A channel where you can request "live" help from a TA during lecture hours by mentioning your table name
I will post a video in the Python Teams channel illustrating this in more detail.
The video support is quite handy, it allows screen sharing, and also allows you to let others control your screen for technical support emergencies.
You are welcome to "sit together" virtually on Teams whenever you want, also outside of lecture hours! However, the course team (TAs / teachers) will only provide support in Teams during official lecture hours.
## Support Forum
In addition, for python, we will also work with an external support forum:
https://tn1405-forum.quantumtinkerer.tudelft.nl/
You have all been sent an invitation to join the forum at your TU Delft student email address. Note you will have to create a separate password. (If you forget the password, it is easy to reset using your email address.)
The forum is a place where you can ask questions about the course material. **What is the difference between the forum and asking for help in teams?** There are three things:
* The answers the course team provide will be visible to everyone so that people who have a similar problem can already find the answer
* You might be able to get help from other students as well who had or are having similar problems
* **Questions in the forum will also be answered outside of office hours**
Some advice and ground rules:
* Don't be shy: just post. We will do our best to answer all questions politely and respectfully.
* Try to include as much info as you can in your post: details will help us figure out your problem. Posting error messages is highly valuable.
* **Don't post solution code to the assignments!** Question about problems with the assignment are welcome, but please formulate your questions in words. If we get stuck trying to figure it out, we will ask you to send the code to the course team in a personal message.
* When you post or reply, do your best to be polite and respectful: let's make this a comfortable place for everyone!
---
jupyter:
jupytext:
formats: ipynb,md
text_representation:
extension: .md
format_name: markdown
format_version: '1.2'
jupytext_version: 1.3.0
kernelspec:
display_name: Python 3
language: python
name: python3
---
# The Python Online Classroom in TN1405-P 2020/2021
Due to the circumstances, the course in the 2020/2021 academic year will be run primarily online. Fortunately there are many great tools that will enable you to learn online, work online, and intearct with us and each other online. Particularly for programming, this can be very effective.
For the python, there are three important online tools which we will use in the following way:
* **Brightspace / Vocareum:** Where you log in and work
* **Microsoft Teams:** A "virtual classroom"
* **Support Forum:** Where you can post questions both inside and outside of lecture hours
In the sections below, I will describe in a bit more detail how we will use them.
## Brightspace / Vocareum
This is where you we will post information and the material for you to work on. Vocareum is our cloud-based computing platform, and is accessed by links from inside Brightspace.
## Microsoft Teams
We will use Microsoft teams as an online classroom where you can work and interact with the teachers, the TAs, and with each other.
Microsoft teams is a "chat" based communications tool that organises discussions inside a "team" into "channels", similar to the platform discord (https://discord.com/) that some of you may be familiar with from online gaming communities.
For Python, the following channels are relevant:
* **Python:** Where I will post things like instructional videos and other information that is hard to post on brightsapce
* **Tafel 01-10:** Virtual "tables" where you can work with other students using text chat, video chat, posting images / screenshots, and sharing documents
* **TA gevraagd:** A channel where you can request "live" help from a TA during lecture hours by mentioning your table name
I will post a video in the Python Teams channel illustrating this in more detail.
The video support is quite handy, it allows screen sharing, and also allows you to let others control your screen for technical support emergencies.
You are welcome to "sit together" virtually on Teams whenever you want, also outside of lecture hours! However, the course team (TAs / teachers) will only provide support in Teams during official lecture hours.
## Support Forum
In addition, for python, we will also work with an external support forum:
https://tn1405-forum.quantumtinkerer.tudelft.nl/
You have all been sent an invitation to join the forum at your TU Delft student email address. Note you will have to create a separate password. (If you forget the password, it is easy to reset using your email address.)
The forum is a place where you can ask questions about the course material. **What is the difference between the forum and asking for help in teams?** There are three things:
* The answers the course team provide will be visible to everyone so that people who have a similar problem can already find the answer
* You might be able to get help from other students as well who had or are having similar problems
* **Questions in the forum will also be answered outside of office hours**
Some advice and ground rules:
* Don't be shy: just post. We will do our best to answer all questions politely and respectfully.
* Try to include as much info as you can in your post: details will help us figure out your problem. Posting error messages is highly valuable.
* **Don't post solution code to the assignments!** Question about problems with the assignment are welcome, but please formulate your questions in words. If we get stuck trying to figure it out, we will ask you to send the code to the course team in a personal message.
* When you post or reply, do your best to be polite and respectful: let's make this a comfortable place for everyone!