Skip to content
Snippets Groups Projects
Additional Programming Concepts in Python.md 23.1 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
---
jupyter:
  jupytext:
    formats: ipynb,md
    text_representation:
      extension: .md
      format_name: markdown
      format_version: '1.1'
      jupytext_version: 1.2.2
  kernelspec:
    display_name: Python 3
    language: python
    name: python3
---

<!-- #region -->
# 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. 

*(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

### 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: 

```
my_tuple = (a, b, c, ...etc...)
```

As a concrete example, this will create a tuple of three integers:
<!-- #endregion -->

```python
tup1 = (5,6,7)
print(tup1)
```

Like the other data types we've see, we can see the tuples we create using `%whos`:

```python
%whos
```

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:

```python
len(tup1)
```

Note that tuples do not have to contain integers, they can contain any type of data:

```python
# A tuple of strings
str_tup = ('foo', 'bar')
print(str_tup)
```

Different than how numpy arrays are typically used, tuples can even be mixed, with each element of a different type:

```python
mixed_tup = (1, 1.05, 7+3j, 'foo')
print(mixed_tup)
```

And you can even have tuples of tuples:

```python
tup_of_tup = (str_tup, mixed_tup)
print(tup_of_tup)
```

Tuples support all the same indexing and slicing as arrays. 


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:

```python
print(tup_of_tup)
print(tup_of_tup[0])
print(tup_of_tup[0][0])
```

### Looping over tuples without using indices

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. 

For example, to print all of entries of a `tuple` out in order, we can use directly following:


```python
for n in tup1:
    print(n)
```

During each subsequent iteartion of the loop, the variable `n` will be assigned to the next item that is stored in the tuple. 

<!-- #region -->
## Lists

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:

```
my_list = [a, b, c, ...etc...]
```
<!-- #endregion -->

```python
l1 = list(range(10))
l1
```

Like tuples, you can extract single elements of the list using indexing, and extract portions of the list using slicing:

```python
print(l1[0])
print(l1[0:5])
```

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"

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:

```python
l1 = [5,6,7]
l1[2] = 8
```

If I try this with a tuple, I will find that I can't do it!

```python
t1 = (5,6,7)
t1[2] = 8
```

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:

```python
l2 = list(range(10))
print(l2)
```

```python
# Replace three entries by zeros
l2 = list(range(10))
l2[4:7] = [0,0,0]
print(l2)
```

```python
# Remove entries from a list by replacing them with an empty list []
l2 = list(range(10))
l2[4:7] = [] 
print(l2)
```

### 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:

```python
# This will add an element to the end of the list
l1.append(10)
l1
```

```python
# This will remove an element from the end of the list
l1.pop()
l1
```

There are many more functions built into lists, some of which you can find here:

https://docs.python.org/3/tutorial/datastructures.html


### The problem with lists for scientific computing

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.

A vector is a collection of numbers in a one-dimentional array:

$$
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? 

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]
$$

Let's check if this works with lists

```python
l = [1, 2, 3, 4, 5]
print(2*l)
```

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:

```python
print(l+l)
```

Addition makes the list twice as long? And:

```python
print(l-l)
```

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.


## Dictionaries

Another useful data type in python is a "dictionary":

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 `}`. 

Here we will create an empty dictionary and start filling it:

```python
delft_lunch_rating = {}
delft_lunch_rating['greek olive'] = 10
delft_lunch_rating['brandmeester'] = 7
delft_lunch_rating['aula'] = "expensive"
delft_lunch_rating['citg'] = "bad"
delft_lunch_rating['doner'] = "good but a bit salty"
```

This is what our dictionary looks like:

```python
print(delft_lunch_rating)
```

I can then look up values in my dictionary using the "keys":

```python
delft_lunch_rating['aula']
```

There are also functions for getting all the keys:

```python
delft_lunch_rating.keys()
```

My dictionaries can also hold lists if I want:

```python
delft_lunch_rating["greek olive"] = ['good', 10]
```

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. 


## Strings

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). 

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:

```python
s1 = "This is a string"
```

Indexing a string returns the characters of the string:

```python
print(s1[0])
```

We can also slice:

```python
print(s1[0:6])
```

Strings do not allow you to directly change 


### Built-in string functions

Strings have a bunch of useful built-in functions: 

https://docs.python.org/3/library/stdtypes.html#string-methods

some of which we will look at here:

### 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:

```python
s1.split()
```

Passing `.` as an argument, `split()` will use that as a separator, which is useful for working with filenames:

```python
input_file = 'myfile.dat'
output_file = input_file.split('.')[0]
output_file += "_processed.dat"
print(output_file)
```

### Replacing parts of strings

The function `replace()` replace substrings in your string for you:

```python
s2 = "This is a long sentence. It is a good idea to end it."
print(s2)
print(s2.replace(" is", " was"))
```

Note that without the space, it will also replace the "is" in "This":

```python
print(s2)
print(s2.replace("is", "was"))
```

### Testing for the contents of a string

You can check if a substring is found inside a string using the `in` logical operator:

```python
if "this" in "somewhere in this sentence":
    print("We found a 'this'")
```

```python
# It is case sensitive:
if "this" in "This is a sentence":
    print("This will not get printed")
```

```python
# But you can use the .lower() function of a string to do case insensitive checks
s3 = "This is a sentence"
if "this" in s3.lower():
    print("Using .lower(), s3 is converted to all lower-case:\n")
    print("s3.lower = '%s'\n" % s3.lower())
    print("And now we do find the substring 'this'")
```

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

Note that if you want to print a backslash `\`, you need to put a double backslash in your string: `\\`.


### String formatting

Until now, we have been printing values of our variables using the standard `str()` conversion of numbers to strings:

```python
a = 11/300
print("The value of a is", a)

# The above print() statement is equivalent to:

output = "The value of a is"
output += " "
output += str(a)
print(output)
```

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:

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. 

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:

```python
# Floating point format with 4 digits
print("The value of a is %.4f" % a)
```

```python
# Exponential notation with two digits
print("The value of a is %.2e" % a)
```

```python
# A string with the formatting not at the end
print("The value of a is %.2e seconds" % a)
```

# Some additional matrix creation routines

There are several functions for making matrices which you may find useful someday: 

https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html

including this one which I use often:

```python
# The identity matrix
print(np.eye(10))
```

```python
# A band diagonal matrix
print(np.eye(10,k=-1))
```

## Mutable objects and "call by reference"

### 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.

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:

```python
a = 5
b = a
print(b)
```

What happens if we change the value of `a` after the statment `b = a`? For example:

```python
a = 5
b = a
a = 6
```

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:

```python
a = 5
b = a
a = 6
print(b)
```

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`.

```python
a = [2,1]
b = a
a[0] = 1
```

Now question: did `a[0] = 1` change the value of of `b`? Let's check:

```python
print(b)
```

Changing the values of `a` also changed list `b` for some reason? **WHY!!!!?????!!! WHAT IS GOING ON?!!?**

### "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. 

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. 

This procedure is called "call by value" in programming languages, and is illustrated here: 

<img src="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:

<img src="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.

"Call by reference" also holds for when you are passing variables to functions:

```python
def set_first_entry_to_zero(x):
    x[0] = 0

a = [1,2]
set_first_entry_to_zero(a)
print(a)
```

We can see that our function changed the value of the variable mylist! This was not possible with integers for example:

```python
def set_to_zero(x):
    x = 0

a = 1
set_to_zero(a)
print(a)
```

### 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. 

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. 

```python
a = [2,1]
b = a.copy()
print(b)
a[0] = 1
print(b)
```

Now, `b` is unaffected by your changes to `a` because the name `b` points to a new copy of the array in memory.


## Interactive plots with ipywidgets

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`.

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:

```python
from ipywidgets import interact

v0 = 10 # m/s
g = 9.8 # m/s^2

# We will allow theta to be adjusted and start it at 45 degrees
def update_plot(theta=45):
    theta *= np.pi/180 # convert to radians
    y = -g/(2*v0**2*np.cos(theta)**2)*x**2 + x*np.tan(theta)
    plt.plot(x,y)
    plt.ylim(-1,6) # Manually set the ylimits
    plt.xlabel("Distance (m)")
    plt.ylabel("Height (m)")
    plt.axhline(0, ls=":", c="grey")
    plt.show()
    
# 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))
```

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:

```python
def update_plot2(slope=0.5):
    line = t*slope
    plt.plot(t,v, '.')
    plt.plot(t,line, lw=4)
    plt.xlabel("Time (s)")
    plt.ylabel("Voltage (V)")
    plt.show()

interact(update_plot2, slope=(0,10,0.1))
```

It is also easy to make two sliders:

```python
def update_plot3(slope=0.5, offset=0):
    line = t*slope+offset
    plt.plot(t,v, '.')
    plt.plot(t,line, lw=4)
    plt.xlabel("Time (s)")
    plt.ylabel("Voltage (V)")
    plt.show()

interact(update_plot3, slope=(0,10,0.1), offset=(-4,3,0.2))
```

<!-- #region -->
## Functions

### 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:

```
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. 

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. 
<!-- #endregion -->

```python
def print_status4(x, long=True):
    if long:
        print("The value of the first input variable is ", x)
    else:
        print("Val is ", x)

print_status4(1)
print_status4(2.5, long=True)
print_status4(2.4, long=False)
```

<!-- #region -->
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:

```
def myfunction(x, var1=1, var2=4):
    ...
```

then both of these would do the same thing:

```
myfunction(1,var1=3, var2=54)
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:
<!-- #endregion -->

```python
def myfun(x,y):
    print("x is", x)
    print("y is", y)    
```

```python
myfun(1,2)
```

```python
myfun(2,1)
```

```python
myfun(x=1,y=2)
```

```python
myfun(y=2,x=1)
```

### Python Error Messages with functions

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. 

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.

```python
import matplotlib.pyplot as plt
plt.plot([1,2], [1,2,3])
```

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...). 

At the top, it shows us the part of our code that triggered the error:

<img src="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". 

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:

<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. 

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:

`plt.plot([1,2,3], [1,2,3,])`

then the error goes away:

```python
plt.plot([1,2,3], [1,2,3,])
```

## Learning objectives list

Not crucial since this notebook is optional, but maybe useful to have.

**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 loop over tuples and lists without indexing
* 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 use built-in functions of lists 
* 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 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 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 use the `ipywidgets` `interact()` function to explore functions using sliders



```python

```