Workshop 3 - Practice Makes Perfect

There is a sign-in sheet, sign in or you wont get credit for attendance today!


Goals for Today:

You can download todays notebook from github.com/dahlend/Physics77Fall17

0 - Review

Reminder cheat sheet:

Types of Variables (not complete list)

Type Name Example
int() Integer 1337
float() decimal number -2345.12
complex() complex number 7-1j
string() text "Hello World"
list() list of things ['c', 1, 3, 1j]
bool() boolean (True or False) True

Comparing things

Operator Name
> greater than
< less than
== equal
>= greater than or equal
<= less than or equal
!= not equal

If Statements

if (some condition):  
    if the condition is true, run code which is indented here
else:  
    run this code if the condition is not met

For Loops

some_list = [1, 2, 'text', -51.2]
for x in some_list:
    print(x)
    if type(x) == int:
        print("x is an integer!")

1 - Whitespace

Whitespace is a name for the space character '  ' or a tab, which is written '\t'. Whitespace is very important in python (This is not always true with other languages), it is used to signify heirarchy.

What does that mean? Lets say we have an 'if' statement:

if 6 < 5:
    print("Hi im filler text")
    print("see any good movies lately?")
    print("ok, 6 is less than 5. That's not true!")
print("If statement is over")

Whitespace is how you tell python what lines of code are associated with the if statement, so in this case we should see only the output:

"If statement is over"

Python treats all code which is at the same number of spaces as being in the same sort of 'block', so above, the 3 print lines 'inside' the if statement will be run when the statement is true.

Having to add space before lines like this happens any time you have a line of code that ends with a ':'

Examples of this are:

# If statements
if True:
    print("Doing stuff")
else:
    print("Doing other stuff")

# For loops
for x in some_list:
    print('x is equal to ', x)
    print('x + 5 = ', x + 5)

# Defining your own function
def my_function(x):
    print("my_function was given the variable x=", x)
    return x

When you combine multiples of these together, you have to keep indenting!

x = 6
for y in range(10):
    print("y = ", y)  # This will run for every y in [0,...,9]
    if x > y:
        print(x)    # this only runs if x > y, for every y in [0,...,9]
    else:
        print("y is bigger than x!")

2 - Packages (AKA Libraries, Modules, etc.)

Python itself has a limited number of tools available to you. For example, lets say I want to know the result of some bessel function. The average python user doesn't care about that, so its not included in base python. But if you recall, on the first day I said, 'someone, somewhere, has done what I'm trying to do'. What we can do is use their solution.

Libraries, like their namesakes, are collections of information, in this case they generally contain functions and tools that other people have built and made available to the world.

The main packages we will use in this class are:

  • Numpy (Numerical Python) - essential mathematical methods for number crunching
  • MatPlotLib - the standard plotting toolset used in python
  • Scipy (Scientific Python) - advanced mathematical tools built on numpy

Lets take a look at matplotlib's website https://matplotlib.org/

All of these packages are EXTREMELY well documented, hopefully you will get comfortable looking at the documentation for these tools by the end of the semester.

Example:


In [1]:
import matplotlib.pyplot as plt
import numpy as np


# Base Python range() doesn't allow decimal numbers
# numpy improved and made thier own:

t = np.arange(0.0, 1., 0.01)
y = t**3.
plt.plot(100 * t, y)

plt.xlabel('Time (% of semester)')
plt.ylabel('Enjoyment of Fridays')
plt.title('Happiness over Time')
plt.show()


Breaking it down:

I want access to numpy's functions, so I need to 'import' the package. But 'numpy' is anoying to type, so I'll name it np when I use it.

import numpy as np

This means all of numpy is available to me, but I have to tell python when I'm using it.

np.arange(0, 1, 0.01)

This says, there is a function called arange() inside numpy, so I'm telling python to use it.

Periods here are used to signify something is INSIDE something else, IE:

np.arange is saying look for a thing called 'arange' inside np (which is a shorthand for numpy)

np.arange
plt.plot

3 - Problems

Problem 0

Plot a sin wave using np.sin(), the example above is a good starting point!

Hint: np.sin can accept a list of numbers and returns the sin for each of the numbers as another list.


In [2]:
# Your Code Here

Problem 1

We are going to plot a sawtooth wave. This is trickier, since there isn't a numpy function for it!

You will have to construct a list of numbers which contains the correct y values.

This list of values will have to be something like:

y =  [0, 1, 2, 3, 4, 5, 0, 1, 2 ...]

In this case, there we have the numbers from 0 to 5 being repeated over and over.

Goals for the sawtooth plot:

  • go from 0 to n-1 - in the example above, n=6, where n is how many numbers are being repeated
  • have a total of length numbers in the list y

Steps to pull this off:

1) Start with an empty list, this can be done with y = [ ]

We will then loop length times, adding the right value to the end of the list y

2) Make a for loop going from 0 to length, and call the iteration value i
3) Now we have to add the correct value to the end of the list y, for the first n steps of the loop this is easy, we just are adding i.

Thinking this through:
i = 0, we add 0 to the end of the list
i = 1, we add 1 to the end of the list
...
i = n, we add 0 to the end of the list
i = n + 1, we add 1 to the end of the list
i = n + 2, we add 2 to the end of the list
...
i = 2*n, we add 0 to the end of the list
i = 2*n+1, we add 1 to the end of the list

Hint
Remember the % operator from last week?
5 % 2 = 1 ( the remainder after division is 1)

(3*n) % n = 0 $\qquad$ $\frac{3n}{n}$ is 3 remainder 0
(3*n + 1) % n = 1 $\qquad$ $\frac{3n+1}{n}$ is 3 remainder 1

4) Once we know the correct value from (3), we can add it to the list y with

y.append(value_from_3)

5) Plot it!

Lists can have values "appended" to them, in other words you can add more things to the list you have already made.


In [3]:
n = 20
length = 100

# Your code here

Problem 2

Fun with lists!

Lists can do all sorts of things, for example, we can repeat entries of a list many times:


In [4]:
list_of_single_thing = ['hello']
5 * list_of_single_thing


Out[4]:
['hello', 'hello', 'hello', 'hello', 'hello']

In [5]:
# Look familiar?
4 * [0, 1, 2, 3, 4, 5]


Out[5]:
[0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]

Now redo problem 1 but using this, to get this to work you will have to build a list of the correct length.

range() isn't actually a list, but you can turn it into one!

list(range())

There are many ways to achieve the same goal when programming, some take less effort than others.


In [6]:
n = 20
length = 100

# Your code here

Problem 3

Now we will play with another aspect of lists, indexing.

Given a list of numbers x, set every 5th number to 2.

In order to do this, we need to have a way of accessing an element of the list.

x[0] is the first element of the list
x[1] is the second
x[2] is the third
...
x[n] is the n+1 th

this is called 0-indexing, because we started counting at 0 (if you were wondering why i always start counting from 0 in this class, this is why)

We can set a value of a list to something like so:

x[7] = 2

now the 8th element of the list x is 2.

So to solve this problem, I'm providing you a list x, containing 100 zeros.

Set every 5th to a 2, and plot the result.

Steps:
1) Make a for loop going from 0 to 100 in steps of 5

hint range(0, 100, 5)

2) for each step in the for loop set the x[i] number to 2

3) plot the result


In [7]:
# Here is a list of 100 zeros
x = 100*[0]

Problem 4

Tell me the average value, and standard deviation, of a list of numbers I provide:

numpy has a function for this, google is your friend.


In [8]:
x = np.log(np.arange(1, 100) ** 3)

# Your code here