![]() |
Jupyter at Bryn Mawr College |
|
|
Public notebooks: /services/public/dblank / CS245 Programming Languages / 2016-Fall / Labs |
We will be using the Jupyter notebook for many activities this semester. Every notebook has an associated language called the "kernel". We will be using in the Python 3 kernel from the IPython project.
For more information on how to use the notebook, please read the following (which is also a notebook written by a Bryn Mawr student):
Python is a programming language that has been under development for over 25 years [1].
This Chapter will not cover everything in Python. If you would like, please consider the following resources:
Getting Started with Python:
Learning Python in Notebooks:
This is handy to always have available for reference:
Python Reference:
Python is an imperative language based on statements. That is, programs in Python consists of lines composed of statements. A statement can be:
1
2
-3
1
2
3.14
'apple'
"apple"
Notice that the Out might not match exactly the In. In the above example, we used double-quotes but the representation of the string used single-quotes. Python will default to showing representations of values using single-quotes, if it can.
True
False
Python has three very useful data structures built into the language:
List is a mutable list of items. Tuple is a read-only data structure (immutable).
[1, 2, 3]
(1, 2, 3)
1, 2, 3
{"apple": "a fruit", "banana": "an herb", "monkey": "a mammal"}
{"apple": "a fruit", "banana": "an herb", "monkey": "a mammal"}["apple"]
There are two ways to call functions in Python:
Infix operator name:
1 + 2
abs(-1)
import operator
operator.add(1, 2)
Evaluating and display result as an Out, versus evaluating and printing result (side-effect).
print(1)
None
def plus(a, b):
return a + b
plus(3, 4)
def plus(a, b):
a + b
plus(3, 4)
What happened? All functions return something, even if you don't specify it. If you don't specify a return value, then it will default to returning None
.
"a" + 1
Python error messages
TypeError: Can't convert 'int' object to str implicitly
Above the error message is the "traceback" also called the "call stack". This is a representation of the sequence of procedure calls that lead to the error. If the procedure call originated from code from a file, the filename would be listed after the word "File" on each line. If the procedure call originated from a notebook cell, then the word "ipython-input-#-HEX".
1 == 1
[] is []
list() is list()
tuple() is tuple()
57663463467 is 57663463467
The Zen of Python:
import this
Python evolves. But there are limits:
from __future__ import braces
Is not always clear:
y = 0
for x in range(10):
y = x
x
[x for x in range(10, 20)]
x
Python follows the LEGB Rule (after https://www.amazon.com/dp/0596513984/):
x = 3
def foo():
x=4
def bar():
print(x) # Accesses x from foo's scope
bar() # Prints 4
x=5
bar() # Prints 5
foo()
See scope_resolution_legb_rule.ipynb for some additional readings on scope.
def function():
for i in range(10):
yield i
function()
for y in function():
print(y)
def do_something(a, b, c):
return (a, b, c)
do_something(1, 2, 3)
def do_something_else(a=1, b=2, c=3):
return (a, b, c)
do_something_else()
def some_function(start=[]):
start.append(1)
return start
result = some_function()
result
result.append(2)
other_result = some_function()
other_result
"List comprehension" is the idea of writing some code inside of a list that will generate a list.
Consider the following:
[x ** 2 for x in range(10)]
temp_list = []
for x in range(10):
temp_list.append(x ** 2)
temp_list
But list comprehension is much more concise.
%matplotlib notebook
After the magic, we then need to import the matplotlib library:
import matplotlib.pyplot as plt
Python has many, many libraries. We will use a few over the course of the semester.
To create a simple line plot, just give a list of y-values to the function plt.plot().
plt.plot([5, 8, 2, 6, 1, 8, 2, 3, 4, 5, 6])
But you should never create a plot that doesn't have labels on the x and y axises, and should always have a title. Read the documentation on matplotlib and add labels and a title to the plot above:
http://matplotlib.org/api/pyplot_api.html
Another commonly used library (especially with matplotlib is numpy). Often imported as:
Are functions that capture some of the local bindings to variables.
def return_a_closure():
dict = {}
def hidden(operator, value, other=None):
if operator == "add":
dict[value] = other
else:
return dict[value]
return hidden
thing = return_a_closure()
thing("add", "apple", 42)
thing("get", "apple")
thing.dict
Where is dict?
See http://www.programiz.com/python-programming/closure for more examples.