python behaves like a calculator


In [ ]:
8*8

Predict the following output


In [ ]:
print((5+5)/25)
print(5 + 5/25)

python does order of operations, etc. just like a calculator

Most of the notation is intuitive.

Write out the following in a cell. What value to you get?

$$ (5 \times 5 + \frac{4}{2} - 8)^{2}$$

In [ ]:

Most notation is intuitive. Only weirdo is that "raise x to the power of y" is given by x**y rather than x^y.

What is the value of $sin(2)$?


In [ ]:
sin(2)

Python gives very informative errors (if you know how to read them). What do you think NameError means?

NameError means that the current python "interpreter" does know what sin means

To get access to more math, you need

import math


In [ ]:
import math

math.sin(2)

Once you have math imported, you have access to a whole slew of math functions.


In [ ]:
print(math.factorial(10))
print(math.sqrt(10))
print(math.sin(math.pi))
print(math.cos(10))
print(math.exp(10))
print(math.log(10))
print(math.log10(10))

If you want to see what the math module has to offer, type math. and then hit TAB.


In [ ]:
# for example
math.

You can also get information about a function by typing help(FUNCTION). If you run the next cell, it will give you information about the math.factorial function.


In [ ]:
help(math.factorial)

Variables

Predict what will happen.


In [ ]:
x = 5
print(x)

In [ ]:
x = 5
x = x + 2
print(x)

In python "=" means "assign the stuff on the right into the stuff on the left."

Predict what will happen.


In [ ]:
x = 7 
5*5 = x
print(x)

What happened?

SyntaxError is something python can't interpret.

In python, = means store the output of the stuff on the right in the variable on the left. It's nonsensical to try to store anything in 5*5, so the command fails.

Predict what will happen.


In [ ]:
this_is_a_variable = 5
another_variable = 2
print(this_is_a_variable*another_variable)

Variables can (and should) have descriptive names.

Implement

Stirling's approximation says that you can approximate $n!$ using some nifty log tricks.

$$ ln(n!) \approx nln(n) - n + 1 $$

Write code to check this approximation for any value of $n$.


In [ ]:

Summary

  • Python behaves like a calculator (order of operations, etc.).
  • You can assign the results of calculations to variables using "="
  • Python does the stuff on the right first, then assigns it to the name on the left.
  • You can access more math by import math

In [ ]: