Commit 94540f77 authored by Jens Ehlers's avatar Jens Ehlers
Browse files

Python intro update

parent 036628b2
%% Cell type:markdown id: tags:
# Einführung in Python
%% Cell type:markdown id: tags:
Dieses Notebook enthält eine kurze Einführung in die Programmiersprache [Python](https://www.python.org/). Bitte unbedingt Python in Version 3 verwenden! Die Quelle der folgenden Anleitung ist: [Bryn Mawr College](https://jupyter.brynmawr.edu/services/public/dblank/CS245%20Programming%20Languages/2016-Fall/Labs/Chapter%2002%20-%20Introduction%20to%20Python.ipynb).
---
%% Cell type:markdown id: tags:
**Python** is a programming language that has been under development for over [25 years](https://en.wikipedia.org/wiki/History_of_Python).
This notebook will not cover everything in Python. If you would like, please consider the following resources:
**Getting Started with Python**:
* https://www.codecademy.com/learn/learn-python-3
* http://docs.python-guide.org/en/latest/intro/learning/
**Python Reference**:
* https://docs.python.org/3/reference/
%% Cell type:markdown id: tags:
## Statements
%% Cell type:markdown id: tags:
Python is an [imperative language](https://en.wikipedia.org/wiki/Imperative_programming) based on [statements](https://en.wikipedia.org/wiki/Statement_(computer_science)). That is, programs in Python consists of lines composed of statements. A statement can be:
* a single expression
* an assignment
* a function call
* a function definition
* a statement; statement
%% Cell type:markdown id: tags:
### Expressions
%% Cell type:markdown id: tags:
* Numbers
* integers
* floating-point
* complex numbers
* strings
* boolean values
* lists and dicts
%% Cell type:markdown id: tags:
#### Numbers
%% Cell type:code id: tags:
``` python
1
```
%% Output
1
%% Cell type:code id: tags:
``` python
1
2
```
%% Output
2
%% Cell type:code id: tags:
``` python
3.14
```
%% Output
3.14
%% Cell type:markdown id: tags:
#### Strings
%% Cell type:code id: tags:
``` python
'apple'
```
%% Output
'apple'
%% Cell type:code id: tags:
``` python
"apple"
```
%% Output
'apple'
%% Cell type:markdown id: tags:
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.
%% Cell type:markdown id: tags:
#### Boolean Values
%% Cell type:code id: tags:
``` python
True
```
%% Output
True
%% Cell type:code id: tags:
``` python
False
```
%% Output
False
%% Cell type:markdown id: tags:
#### Lists and Dicts
%% Cell type:markdown id: tags:
Python has three very useful data structures built into the language:
* dictionaries (hash tables): {}
* lists: []
* tuples: (item, ...)
List is a mutable list of items. Tuple is a read-only data structure (immutable).
%% Cell type:code id: tags:
``` python
[1, 2, 3]
```
%% Output
[1, 2, 3]
%% Cell type:code id: tags:
``` python
(1, 2, 3)
```
%% Output
(1, 2, 3)
%% Cell type:code id: tags:
``` python
1, 2, 3
```
%% Output
(1, 2, 3)
%% Cell type:code id: tags:
``` python
{"apple": "a fruit", "banana": "an herb", "monkey": "a mammal"}
a = {"apple": "a fruit", "banana": "an herb", "monkey": "a mammal"}
a
```
%% Output
{'apple': 'a fruit', 'banana': 'an herb', 'monkey': 'a mammal'}
%% Cell type:code id: tags:
``` python
{"apple": "a fruit", "banana": "an herb", "monkey": "a mammal"}["apple"]
a["apple"]
```
%% Output
'a fruit'
%% Cell type:code id: tags:
``` python
a = [1, 2, 3]
b = (1, 2, 3)
c = {"apple": "a fruit", "banana": "an herb", "monkey": "a mammal"}
type(a), type(b), type(c)
```
%% Output
(list, tuple, dict)
%% Cell type:markdown id: tags:
### Function Calls
%% Cell type:markdown id: tags:
There are two ways to call functions in Python:
1. by pre-defined infix operator name
2. by function name, followed by parentheses
Infix operator name:
%% Cell type:code id: tags:
``` python
1 + 2
```
%% Output
3
%% Cell type:code id: tags:
``` python
abs(-1)
```
%% Output
1
%% Cell type:code id: tags:
``` python
import operator
operator.add(1, 2)
```
%% Output
3
%% Cell type:markdown id: tags:
#### Print
%% Cell type:markdown id: tags:
Evaluating and display result as an Out, versus evaluating and printing result (side-effect).
%% Cell type:code id: tags:
``` python
print(1)
```
%% Output
1
%% Cell type:markdown id: tags:
### Special Values
%% Cell type:code id: tags:
``` python
None
```
%% Cell type:markdown id: tags:
### Defining Functions
%% Cell type:code id: tags:
``` python
def plus(a, b):
return a + b
plus(3, 4)
```
%% Output
7
%% Cell type:code id: tags:
``` python
def plus(a, b):
a + b
print(plus(3, 4))
```
%% Output
None
%% Cell type:markdown id: tags:
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`.
%% Cell type:code id: tags:
``` python
"a" + 1
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-42f7d05b4f13> in <module>
----> 1 "a" + 1
TypeError: can only concatenate str (not "int") to str
%% Cell type:markdown id: tags:
**How to Read Python Error Messages**
Python error messages
`TypeError: Can't convert 'int' object to str implicitly`
Python error messages `TypeError: can only concatenate str (not "int") to str`
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-...".
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 we see the "ipython-input-...".
%% Cell type:markdown id: tags:
## Equality
%% Cell type:markdown id: tags:
### ==
%% Cell type:code id: tags:
``` python
1 == 1
```
%% Output
True
%% Cell type:code id: tags:
``` python
[1, 2] == [1, 2] # list objects compared by value
```
%% Output
True
%% Cell type:markdown id: tags:
### is
%% Cell type:code id: tags:
``` python
[1, 2] is [1, 2] # list objects compared by reference
```
%% Output
False
%% Cell type:code id: tags:
``` python
{"a": 1, "b": 2} is {"a": 1, "b": 2} # dict objects compared by reference
```
%% Output
False
%% Cell type:code id: tags:
``` python
(1, 2) is (1, 2) # tuples compared by value
(1, 2) is (1, 2) # if tuples are compared by reference or value, depends on your Python version
```
%% Output
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<ipython-input-26-e351903fd900>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
(1, 2) is (1, 2) # tuples compared by value
<ipython-input-26-39c6e37b4335>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
(1, 2) is (1, 2) # if tuples are compared by reference or value, depends on your Python version
True
%% Cell type:code id: tags:
``` python
1 is 1
```
%% Output
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<ipython-input-27-c4ba21148a2b>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
1 is 1
True
%% Cell type:markdown id: tags:
# Advanced Topics
%% Cell type:code id: tags:
``` python
import this
```
%% Output
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
%% Cell type:markdown id: tags:
## Scope of variables
%% Cell type:markdown id: tags:
Is not always clear:
%% Cell type:code id: tags:
``` python
y = 0
for x in range(10):
y = x
```
%% Cell type:code id: tags:
``` python
x
```
%% Output
9
%% Cell type:code id: tags:
``` python
[x for x in range(10, 20)]
```
%% Output
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
%% Cell type:code id: tags:
``` python
x
```
%% Output
9
%% Cell type:markdown id: tags:
## Scope
%% Cell type:markdown id: tags:
Python follows the LEGB Rule (after https://www.amazon.com/dp/0596513984/):
* L, Local: Names assigned in any way within a function (def or lambda), and not declared global in that function.
* E, Enclosing function locals: Name in the local scope of any and all enclosing functions (def or lambda), from inner to outer.
* G, Global (module): Names assigned at the top-level of a module file, or declared global in a def within the file.
* B, Built-in (Python): Names preassigned in the built-in names module : open, range, SyntaxError,...
%% Cell type:code id: tags:
``` python
x = 3
def foo():
x = 4
def bar():
print(x) # accesses x from foo's scope
bar() # prints 4
x = 5
bar() # prints 5
```
%% Cell type:code id: tags:
``` python
foo()
```
%% Output
4
5
%% Cell type:markdown id: tags:
## Generators
%% Cell type:code id: tags:
``` python
def function():
for i in range(10):
yield i
```
%% Cell type:code id: tags:
``` python
function()
```
%% Output
<generator object function at 0x000002122AA82900>
<generator object function at 0x0000017816A305F0>
%% Cell type:code id: tags:
``` python
for y in function():
print(y)
```
%% Output
0
1
2
3
4
5
6
7
8
9
%% Cell type:markdown id: tags:
## Default arguments
%% Cell type:code id: tags:
``` python
def do_something(a, b, c):
return (a, b, c)
```
%% Cell type:code id: tags:
``` python
do_something(1, 2, 3)
```
%% Output
(1, 2, 3)
%% Cell type:code id: tags:
``` python
def do_something_else(a=1, b=2, c=3):
return (a, b, c)
```
%% Cell type:code id: tags:
``` python
do_something_else()
```
%% Output
(1, 2, 3)
%% Cell type:code id: tags:
``` python
def some_function(start=[]):
start.append(1)
return start
result = some_function()
result
```
%% Output
[1]
%% Cell type:code id: tags:
``` python
result.append(2)
other_result = some_function()
other_result
```
%% Output
[1, 2, 1]
%% Cell type:markdown id: tags:
## List comprehension
%% Cell type:markdown id: tags:
"List comprehension" is the idea of writing some code inside of a list that will generate a list. Consider the following:
%% Cell type:code id: tags:
``` python
[x ** 2 for x in range(10)]
```
%% Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
%% Cell type:code id: tags:
``` python
temp_list = []
for x in range(10):
temp_list.append(x ** 2)
temp_list
```
%% Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
%% Cell type:markdown id: tags:
But list comprehension is much more concise.
%% Cell type:markdown id: tags:
## Plotting
%% Cell type:code id: tags:
``` python
%matplotlib inline
```
%% Cell type:markdown id: tags:
After the magic, we then need to import the matplotlib library:
%% Cell type:code id: tags:
``` python
import matplotlib.pyplot as plt
```
%% Cell type:markdown id: tags:
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().
%% Cell type:code id: tags:
``` python
plt.plot([5, 8, 2, 6, 1, 8, 2, 3, 4, 5, 6])
```
%% Output
[<matplotlib.lines.Line2D at 0x21229948be0>]
[<matplotlib.lines.Line2D at 0x17858c222b0>]
%% Cell type:markdown id: tags:
## Closures
%% Cell type:markdown id: tags:
Are functions that capture some of the local bindings to variables.
%% Cell type:code id: tags:
``` python
def return_a_closure():
dict = {}
def hidden(operator, value, other=None):
if operator == "add":
dict[value] = other
else:
return dict[value]
return hidden
```
%% Cell type:code id: tags:
``` python
thing = return_a_closure()
thing("add", "apple", 42)
thing("get", "apple")
```
%% Output
42
%% Cell type:code id: tags:
``` python
thing.dict
```
%% Output
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-51-d5e1343710c5> in <module>
----> 1 thing.dict
AttributeError: 'function' object has no attribute 'dict'
%% Cell type:markdown id: tags:
Where is dict?
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment