Tips and Tricks

The jupyter notebook allows code and markdown. For example:

Heading Level 1

Heading Level 2

Heading Level 3

Heading Level 4

Regular text. Bla bla bla bla bla

math: $f(x) = {x^2}$

Bullet points:

  • first item
  • second item

There are two modes for cells: edit and select

  • edit shows green frame and let's you change the contents of a cell
  • select shows gray frame let's you use keyboard short cuts, such as c, v, x, dd, a, b (copy, paste, cut, delete, new cell above, new cell below)

To know which directory you're in you can use pwd

In [1]:
pwd
Out[1]:
'/home/wendell/code/learnpython'

To get help about functions use "shift + tab"

linspace()

Recap and useful manipulations

In [2]:
%pylab inline
Populating the interactive namespace from numpy and matplotlib

We learned about different types of variables

In [3]:
x = 1
type(x)
Out[3]:
int
In [4]:
x = 1.
type(x)
Out[4]:
float
In [5]:
x = "Hello"
type(x)
Out[5]:
str
In [6]:
x = False
type(x)
Out[6]:
bool

boolean operations

input: 2 booleans, returns: 1 boolean

  • and
  • or

input: 2 numbers, returns: 1 boolean

  • is equal to ==
  • not equal to !=
  • greater/smaller than >/<
  • greater or equal >=
In [7]:
2 >= 2
Out[7]:
True
In [8]:
True > False
Out[8]:
True
In [9]:
1 > 2/2
Out[9]:
False
In [10]:
x = []
type(x)
Out[10]:
list
In [11]:
len([2,3,4])
Out[11]:
3
In [12]:
x = array([1,2,3])
type(x)
Out[12]:
numpy.ndarray
In [13]:
x = array([[1,2,3],[4,5,6]])
In [14]:
print(x)
[[1 2 3]
 [4 5 6]]
In [15]:
x.shape
Out[15]:
(2, 3)
In [16]:
y = np.full((2,3),0)
print(y)
[[ 0.  0.  0.]
 [ 0.  0.  0.]]
/usr/lib/python3.5/site-packages/numpy/core/numeric.py:294: FutureWarning: in the future, full((2, 3), 0) will return an array of dtype('int64')
  format(shape, fill_value, array(fill_value).dtype), FutureWarning)

What are the types of the following variables x?

  • x = [1, 2, 3],
  • x = [1., 2., 3.],
  • x = ["Hello", "World"]
  • x = ["Hello", 1, 5.4]

What are the types of x[1] ?

  • x = [1, 2, 3],
  • x = [1., 2., 3.],
  • x = ["Hello", "World"]
  • x = ["Hello", 1, 5.4]

Consider

  • x = [1, 2, 3]
  • y = array([1,2,3])

What is going on when you try to run the following?

  • x + 1
  • y + 1

Conclusions:

  • lists are of type list even if they carry elements of different types
  • Because list can carry different types [1,2,3] + 1 is not defined
  • for operations on a bunch of numbers use array
In [17]:
#

ways to use "+"

try to run the following line:

In [18]:
[1,2,3] + 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-0f7f56b3e161> in <module>()
----> 1 [1,2,3] + 1

TypeError: can only concatenate list (not "int") to list

error message implies:

[1,2,3] + []

works. Talk to your neighbor and find out how "+" works with lists.

In [19]:
[1,2,3] + ["Hello"]
Out[19]:
[1, 2, 3, 'Hello']

You can use "+" on strings

In [20]:
"Hello" + " " + "World" + "!"
Out[20]:
'Hello World!'

You can think of a string as a list of characters. The variable type is string, not list though!

Indexing/Slicing

slicing with ":"

In [21]:
x = [0,1,2,3,4,5,6,7]
In [22]:
x[:]
Out[22]:
[0, 1, 2, 3, 4, 5, 6, 7]
In [23]:
x[-1]
Out[23]:
7
In [24]:
print(x[0:3])
print(x[3])
[0, 1, 2]
3

Last index is not displayed!

In [25]:
x[2:]
Out[25]:
[2, 3, 4, 5, 6, 7]
In [26]:
print(x[:-2])
print(x[0::3])
[0, 1, 2, 3, 4, 5]
[0, 3, 6]

Indexing works on strings too!

In [27]:
x = "HelloWorld"
In [28]:
x[3:6]
Out[28]:
'loW'

slicing arrays by using list of indices

In [29]:
x = [10,3,4,2,888,99,1000,3]
In [30]:
y = array(x)
In [31]:
ind = [0,3,4,5,7]
In [32]:
y[ind]
Out[32]:
array([ 10,   2, 888,  99,   3])

slicing arrays by using array of booleans

In [33]:
indbool = array([True,False,False,True,True,True,False,True])
In [34]:
y[indbool]
Out[34]:
array([ 10,   2, 888,  99,   3])

Why would that ever be useful?

In [35]:
y < 100
Out[35]:
array([ True,  True,  True,  True, False,  True, False,  True], dtype=bool)
In [36]:
print(y)
print(y < 100 )
[  10    3    4    2  888   99 1000    3]
[ True  True  True  True False  True False  True]

I want to give a challenge that uses smart slicing. Before I just want to make sure everyone understands plotting.

In [37]:
plot([1],[2],"*")
ylim((0,3))
xlim((0,4))
Out[37]:
(0, 4)
In [38]:
plot([1, 1.5],[2, 0.5],"*")
ylim((0,3))
xlim((0,4))
Out[38]:
(0, 4)

smart slicing challenge

Discuss with a partner and explain the output of the following three lines of code:

In [39]:
x = linspace(0,4*pi,num=1000)
y = sin(x)
plot(x[y>0],y[y>0],'*')
Out[39]:
[<matplotlib.lines.Line2D at 0x7f2c866baeb8>]

"if" statements

In [40]:
x = 2
y = 1
if x < y:
    print("x is smaller than y")
else:
    print("x is equal to or larger than y")
x is equal to or larger than y
In [41]:
x = 1
y = 2
if x < y:
    print("x is smaller than y")
elif x == y:
    print("x is equal to y")
else:
    print("x is lager than y")
x is smaller than y
In [42]:
"hello" == "Hello"
Out[42]:
False
In [43]:
[1,3,2] == [1,2,3]
Out[43]:
False

Advanced function challenge:

  • find the definition of the Heaviside step function in its discrete form (wikipedia)
  • define this function in python (name it step(x) )
  • call your function with the argument x = -1, x = 0, x = 1 to check if you did everything correctly
In [44]:
def step(x):
    "This is the heaviside step function. It returns 0 for x values below 0, 1/2 for x = 0, and 1 for x > 0."
    if x < 0:
        return 0
    elif x == 0:
        return 0.5
    else:
        return 1    

For loops

In [45]:
for i in [1,2,3]:
    print(i)
1
2
3
In [46]:
x = [[1,2,3],[4, 5, 6]]
y = array(x)
In [47]:
for i in x:
    print(i)
[1, 2, 3]
[4, 5, 6]
In [48]:
for i in y:
    print(i)
[1 2 3]
[4 5 6]
In [49]:
for i in ["Hello", "World","!","It's","me","!"]:
    print(i)
Hello
World
!
It's
me
!
In [50]:
for apple in ["Hello", "World","!","It's","me","!"]:
    print(apple)
Hello
World
!
It's
me
!
In [51]:
wordlist = ["Hello", "World","!","It's","me","!"]

for word in wordlist:
    print(word)
Hello
World
!
It's
me
!

Conclusion: The place holder is abritrary!

FizzBuzz problem

In [52]:
for i in range(1,36):
    if i%3 == 0 and i%5 == 0:
        print("FizzBuzz")
    elif i%3 == 0:
        print("Fizz")
    elif i% 5 == 0:
        print("Buzz")
    else:
        print(i)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz

Combining plotting and loops

In [53]:
def unit_circle(npoints):
    "This function returns the x and y values of a circle of radius 1 with center (0,0). npoints defines how many points of the circle we sample"
    alpha = linspace(0,2*pi,npoints)
    x = cos(alpha)
    y = sin(alpha)
    return x,y
In [54]:
def r_circle(r,npoints):
    "This functions returns the x and y values of a circle of radius r with the center (0,0). npoints defines how many points we sample"
    alpha = linspace(0,2*pi,npoints)
    x = r*cos(alpha)
    y = r*sin(alpha)
    return x,y
In [55]:
#define parameters for the circle
npoints = 30
r = 4
#calculate data to plot
x = r_circle(r,npoints)[0]
y = r_circle(r,npoints)[1]

# execute the plotting
plot(x,y,"o")
axis('equal')
xlim((-10,10))
Out[55]:
(-10, 10)
In [56]:
npoints = 30
rlist = [0.2,1,2,4,5]
for r in rlist:
    
    #calculate data to plot
    x = r_circle(r,npoints)[0]
    y = r_circle(r,npoints)[1]

    # execute the plotting
    plot(x,y,"o")
    axis('equal')
    xlim((-10,10))