Scientific Programming

LV 707716

Fabien Maussion

How to use these slides

  • <space> : go to the next slide
  • <shift+space>: go back
  • <left right up down arrows>: navigate through the presentation structure
  • <esc>: toggle overview mode



These lecture notes and exercises are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Feel free to use / adapt them, but don't sell them, and share them under the same licence.

Revisions

Basics

Predict the output of the following code:

In [ ]:
a = 2
b = 3
c = a < b
print(c, type(c))

Write this code in a more pythonic way:

In [ ]:
a = 1
if a == 1:
    a *= 3
elif a == 2:
    a *= 3
else:
    a *= 2

Predict the output of the following code:

In [ ]:
range(4) == [0, 1, 2, 3]

Write this code in a more pythonic way:

In [ ]:
aa = [1, 2, 3]
bb = ['a', 'b', 'c']
for i in range(len(aa)):
    print(i, aa[i], bb[i])

Predict the output of the following code:

In [ ]:
sum([i for i in range(5)])

How to write this better?

In [ ]:
d = {'temp':2, 'unit':'°C'}
if 'temp' in d:
    print(d['temp'])
else:
    print('Default temp: 5')

Name each of the statements / concepts in the code below:

In [ ]:
def get_acinn(stat, var, days=3):
    """Some info"""
    return stat

What is printed by this script?

In [ ]:
x = 2
y = 1

def func(x):
    x = x + y
    return x

print(func(x))
print(x)
print(y)

What is a "tuple"?

Explain the code below:

In [ ]:
while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops! That was no valid number. Try again...")

What is the difference between python, cpython and jpython?

What is printed by this script?

In [ ]:
def f(this):
    """That"""
    pass
print(type(f), f.__doc__)

python modules

What is the "standard library"?

What is a "built-in"?

What is pytest good for again?

What happens when I do: import matplotlib?

numpy

What is the shape of b?

In [ ]:
import numpy as np
a = np.arange(6).reshape(2, 3)
b = a[[0, 1], [1, 2]]

Is this valid code?

In [ ]:
a = np.arange(16).reshape(4, 4)
a[1:3, slice(1, 3)] = 1

And this?

In [ ]:
a = np.arange(16).reshape(4, 4)
a[1:3, slice(1, 3)] = [101, 102]

And this?

In [ ]:
a = np.arange(16).reshape(4, 4)
a[1:3, slice(1, 3)] = [[101, 102], [103, 104]]

And this?

In [ ]:
j, i = a.shape

Predict the output of the following code:

In [ ]:
a = np.arange(6)
b = a[2:5]
b *= b
print(a)

Predict the output of the following code:

In [ ]:
a = [1/i for i in range(1, 1000)]
sum(a) == sum(a[::-1])
In [ ]:
np.allclose(sum(a), sum(a[::-1]))

Something new

Other

What happens when you do:

In [ ]:
import antigravity
In [ ]:
import this