Python intro notes
This commit is contained in:
parent
ea7fd79d11
commit
c9cc068203
|
@ -0,0 +1,3 @@
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
__pycache__
|
|
@ -0,0 +1,4 @@
|
||||||
|
# Notes for introductory to Python
|
||||||
|
|
||||||
|
The cource was held by Torstein N-H 27.09.2019.
|
||||||
|
These notes were used loosely and are included for future reference.
|
|
@ -0,0 +1,44 @@
|
||||||
|
# Tools needed to work efficiently with python
|
||||||
|
|
||||||
|
## Python
|
||||||
|
The interpreter, needed to run any python program.
|
||||||
|
|
||||||
|
### MacOS / Linux / BSD
|
||||||
|
Install the newest python available from your package manager.
|
||||||
|
At the moment 3.6 or 3.7.
|
||||||
|
|
||||||
|
### Windows / MacOS
|
||||||
|
Install the newest version from [the python foundation](https://www.python.org/downloads/).
|
||||||
|
|
||||||
|
## PIP
|
||||||
|
A package manager for python libraries (and more). Maybe the best part of python.
|
||||||
|
|
||||||
|
It comes with most new installations of python, if not try the following:
|
||||||
|
|
||||||
|
### MacOS / Linux / BSD
|
||||||
|
Install the newest python available from your package manager.
|
||||||
|
Note that, if python 2 is installed pip will install packages for python2 and pip3 packages for python3.
|
||||||
|
|
||||||
|
### Windows
|
||||||
|
It might come with the python installation.
|
||||||
|
|
||||||
|
Try
|
||||||
|
```
|
||||||
|
python3 -m pip install <package name>
|
||||||
|
```
|
||||||
|
If not, try installing it from wsl.
|
||||||
|
|
||||||
|
If all else fails, it probably includes running random binary scripts as administrator, good luck.
|
||||||
|
|
||||||
|
## A good editor
|
||||||
|
Learning python is mostly useless if you cant write something in it, find a good editor.
|
||||||
|
|
||||||
|
Recommendations:
|
||||||
|
- PyCharm
|
||||||
|
- Spyder
|
||||||
|
- Thonny
|
||||||
|
- VSCode (or VSCodium)
|
||||||
|
- Atom
|
||||||
|
- Emacs
|
||||||
|
- Vim
|
||||||
|
- Notepad++
|
|
@ -0,0 +1,34 @@
|
||||||
|
"""
|
||||||
|
This is a multiline string
|
||||||
|
It is customary to use start the file with a multiline string for documentation.
|
||||||
|
"""
|
||||||
|
|
||||||
|
"And this a single line string"
|
||||||
|
|
||||||
|
'Both types of string can be written with single quotes as well'
|
||||||
|
|
||||||
|
"This string contains a \" escaped with a \\ "
|
||||||
|
|
||||||
|
"If i want a newline\nI can get it along with a\t\tdouble tab in the middle of a line."
|
||||||
|
r"This is a literal string, i can write \n without a newline."
|
||||||
|
|
||||||
|
# Comments are nicer for documentation as they are harder to mistake for code.
|
||||||
|
|
||||||
|
# This is an integer
|
||||||
|
4
|
||||||
|
|
||||||
|
# This is a float
|
||||||
|
3.14
|
||||||
|
|
||||||
|
# And this an integer bound to a variable
|
||||||
|
a = 4
|
||||||
|
|
||||||
|
# Most data can be printed with the print function
|
||||||
|
print("Hello world")
|
||||||
|
|
||||||
|
# Arithmetic works as expected
|
||||||
|
print(4 * 4 + 1 * 3)
|
||||||
|
|
||||||
|
# Note that exponentials and rounding are weird
|
||||||
|
print(3 ** 2)
|
||||||
|
print(int(2.9))
|
|
@ -0,0 +1,69 @@
|
||||||
|
"""
|
||||||
|
Examples of conditionals and loops in python
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
# This is an if statement
|
||||||
|
if True:
|
||||||
|
print("This is true")
|
||||||
|
|
||||||
|
print("Noe mer her...")
|
||||||
|
|
||||||
|
# And this another one
|
||||||
|
if False:
|
||||||
|
print("This will never be printed")
|
||||||
|
|
||||||
|
# Conditions can be more complex
|
||||||
|
if 1 in [3, 2, 1, 0] and "a" != "B":
|
||||||
|
print("This should happen even though it is needlessly complex")
|
||||||
|
|
||||||
|
# And have multiple terms
|
||||||
|
if False:
|
||||||
|
pass
|
||||||
|
elif 2 + 2 == 5:
|
||||||
|
five = 2 + 2
|
||||||
|
else:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Loops also exist, the most normal is for
|
||||||
|
for x in range(1, 11):
|
||||||
|
for y in range(1, 11):
|
||||||
|
print(x * y, end=" \t\t")
|
||||||
|
print()
|
||||||
|
|
||||||
|
for x in ["a", "b", "c"]:
|
||||||
|
print(x)
|
||||||
|
|
||||||
|
# Another example
|
||||||
|
for y in ["Det", "var", "en", "gang", "en", "liste"]:
|
||||||
|
print(y, end=" ")
|
||||||
|
print()
|
||||||
|
|
||||||
|
# Loops can have unknown length
|
||||||
|
i = 0
|
||||||
|
while i <= 10:
|
||||||
|
print("i is <= 10")
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
# The can also be made infinite
|
||||||
|
while True:
|
||||||
|
if i < 5:
|
||||||
|
break
|
||||||
|
|
||||||
|
print("i > 5")
|
||||||
|
if False:
|
||||||
|
continue
|
||||||
|
i -= 1
|
||||||
|
|
||||||
|
|
||||||
|
# Loops can have an else clause
|
||||||
|
while True:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
print("This wont happens because of the break.")
|
||||||
|
|
||||||
|
for i in range(2):
|
||||||
|
if i < -1000:
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
print("This will be printed because the loop exits from its condition, not a break.")
|
|
@ -0,0 +1,47 @@
|
||||||
|
"""
|
||||||
|
About functions in python
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Users may define their own custom functions
|
||||||
|
def temp():
|
||||||
|
return 3
|
||||||
|
|
||||||
|
# And they may be called after they are defined
|
||||||
|
print(temp())
|
||||||
|
|
||||||
|
# They take arguments
|
||||||
|
def temp2(x, y):
|
||||||
|
return x * y
|
||||||
|
|
||||||
|
temp2(1, 4)
|
||||||
|
|
||||||
|
# And be used lazily
|
||||||
|
def foo(y):
|
||||||
|
return bar(y) - 1
|
||||||
|
# foo may not be called here because bar does not yet exist
|
||||||
|
# print(foo(5))
|
||||||
|
def bar(x):
|
||||||
|
return x + 1
|
||||||
|
|
||||||
|
print(foo(5))
|
||||||
|
|
||||||
|
# Type hinting is supported (but not enforced)
|
||||||
|
def strong_typed(text: str, n: int) -> str:
|
||||||
|
nstr = str()
|
||||||
|
for _ in range(n):
|
||||||
|
nstr += text
|
||||||
|
|
||||||
|
return nstr
|
||||||
|
print(strong_typed("Hello world ", 4))
|
||||||
|
|
||||||
|
# Functions can take any number of arguments, optional arguments and and keyword arguments
|
||||||
|
def fancy_func(a, b="Hello", c: int = 8) -> None:
|
||||||
|
d = a + c
|
||||||
|
print(b, d)
|
||||||
|
fancy_func(1, c=6)
|
||||||
|
|
||||||
|
# They don't even need names
|
||||||
|
print((lambda x, y : x * y)(2, 3))
|
||||||
|
|
||||||
|
# Though lambdas are cool, they are rarely used in python
|
||||||
|
# Decorators are often cleaner
|
|
@ -0,0 +1,17 @@
|
||||||
|
"""
|
||||||
|
In python, all things are object.
|
||||||
|
This means that all functionality associated with a piece of data is stored with the data.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Making a new integer with the int constructor:
|
||||||
|
|
||||||
|
a = int(5)
|
||||||
|
b = int(4)
|
||||||
|
|
||||||
|
# Adding them together
|
||||||
|
print(a + b)
|
||||||
|
# Or without the read macro and function call:
|
||||||
|
print(a.__add__(b).__repr__())
|
||||||
|
|
||||||
|
# The most useful method ever
|
||||||
|
print("Hello {}\nI am {}".format("people who are still here", "the master of the .format method on strings"))
|
|
@ -0,0 +1,32 @@
|
||||||
|
"""
|
||||||
|
Skippable if out of time, hot to define ones own objects.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
class MyVector(list):
|
||||||
|
a = 0
|
||||||
|
|
||||||
|
def __init__(self, dim: int, data: list):
|
||||||
|
if dim != len(data):
|
||||||
|
raise ValueError("Wrong dimensions in the vector!!!")
|
||||||
|
self.dim = dim
|
||||||
|
self.data = data
|
||||||
|
|
||||||
|
def __add__(self, other: MyVector):
|
||||||
|
if self.dim != other.dim:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
return MyVector(self.dim, [a + b for a, b in zip(self.data, other.data)])
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return "A vector of dimension {} with data:\n{}".format(self.dim, self.data)
|
||||||
|
|
||||||
|
|
||||||
|
a = MyVector(3, [1, 2, 3])
|
||||||
|
b = MyVector(3, [-1, -4, 8])
|
||||||
|
|
||||||
|
print(a)
|
||||||
|
print(b)
|
||||||
|
|
||||||
|
print(a + b)
|
|
@ -0,0 +1,79 @@
|
||||||
|
"""
|
||||||
|
Good built in data structures is among the most important things in a good language.
|
||||||
|
Python has several.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# The list
|
||||||
|
a = list()
|
||||||
|
a = []
|
||||||
|
a = [1, 3, 4, 5 ,6]
|
||||||
|
|
||||||
|
# They act like expected
|
||||||
|
for item in a:
|
||||||
|
print(item)
|
||||||
|
print("\n\n")
|
||||||
|
|
||||||
|
# They can contain different types
|
||||||
|
b = [1, "Hello", a, 3.14, lambda a : a + 1]
|
||||||
|
|
||||||
|
for item in b:
|
||||||
|
print(item)
|
||||||
|
|
||||||
|
# And be mutated
|
||||||
|
a.append(8)
|
||||||
|
a.extend(["Hello", "World"])
|
||||||
|
a[1] = 100
|
||||||
|
|
||||||
|
print(a)
|
||||||
|
|
||||||
|
print(a[:5])
|
||||||
|
|
||||||
|
print("\n\n\n")
|
||||||
|
|
||||||
|
# They are objects and can be inherited as such
|
||||||
|
print(dir(a))
|
||||||
|
|
||||||
|
class MyList(list):
|
||||||
|
def __repr__(self):
|
||||||
|
return "This is a useless representation"
|
||||||
|
#pass
|
||||||
|
|
||||||
|
b = MyList(a)
|
||||||
|
print(b)
|
||||||
|
|
||||||
|
|
||||||
|
# The dictionary
|
||||||
|
# A mutable fast type agnostic hashed map
|
||||||
|
a = dict()
|
||||||
|
a = {}
|
||||||
|
a = {2: "Hello world", 3: b, 8: 6.12345}
|
||||||
|
# Note that all keys must be hashable
|
||||||
|
# a[["Not working"]] = 3
|
||||||
|
a[3] = ["This might work", "I think"]
|
||||||
|
print(a)
|
||||||
|
|
||||||
|
# They can be mutated
|
||||||
|
a[2] = 5
|
||||||
|
del a[3]
|
||||||
|
|
||||||
|
print(a)
|
||||||
|
|
||||||
|
# The keys and values can be easily red
|
||||||
|
print(a.keys())
|
||||||
|
print(a.values())
|
||||||
|
|
||||||
|
|
||||||
|
# The set
|
||||||
|
|
||||||
|
# They act like keys in dictionaries, assuming this makes using them easy
|
||||||
|
a = set()
|
||||||
|
a = {'apple', 'orange', 'apple', 'banana', 3, 3, 3, 3, 3}
|
||||||
|
print(a)
|
||||||
|
|
||||||
|
# Lists and set can be made from each other
|
||||||
|
a = [1, 2, 3, 2, 1, 2, 3, 2, 1]
|
||||||
|
b = set(a)
|
||||||
|
c = list(b)
|
||||||
|
print(a)
|
||||||
|
print(b)
|
||||||
|
print(c)
|
|
@ -0,0 +1,32 @@
|
||||||
|
"""
|
||||||
|
Some useful functions that should be mentioned
|
||||||
|
Most are used on lists
|
||||||
|
"""
|
||||||
|
|
||||||
|
# zip
|
||||||
|
for a, b in zip([1, 2, 3, 4], [3, 2, 1]):
|
||||||
|
print("Found {} and {}, added it is {}.".format(a, b, a+b))
|
||||||
|
|
||||||
|
# map
|
||||||
|
print()
|
||||||
|
mapped = map(lambda x: 2 * x, [1, 2, 0])
|
||||||
|
print(mapped)
|
||||||
|
print(list(mapped))
|
||||||
|
|
||||||
|
print()
|
||||||
|
mapped = map(lambda a, b: a - b, [5, 3, 0], [2, 3, -5, 8])
|
||||||
|
print(mapped)
|
||||||
|
print(list(mapped))
|
||||||
|
|
||||||
|
# filter
|
||||||
|
print()
|
||||||
|
filtered = filter(lambda x: x == 3 or x is not None and x % 3 == 1, [3, 4, None, 11, 12, 13])
|
||||||
|
print(filtered)
|
||||||
|
print(list(filtered))
|
||||||
|
|
||||||
|
# div. normal utils
|
||||||
|
print()
|
||||||
|
print(len([1, 2, 3]))
|
||||||
|
print(max([1, 2, 3]))
|
||||||
|
print(min([1, 2, 3]))
|
||||||
|
print(sorted([1, 3, 2]))
|
|
@ -0,0 +1,32 @@
|
||||||
|
"""
|
||||||
|
IO is boring but useful, here is how.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Input and output from the user is easy.
|
||||||
|
a = input("Some prompt here: ")
|
||||||
|
print(a)
|
||||||
|
|
||||||
|
# Input from files are a bit more tricky
|
||||||
|
|
||||||
|
# The way taught in ITGK
|
||||||
|
f = open("file.txt")
|
||||||
|
f.close()
|
||||||
|
|
||||||
|
# The correct way
|
||||||
|
|
||||||
|
|
||||||
|
with open("file.txt", "r") as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
for line in lines:
|
||||||
|
print(line)
|
||||||
|
|
||||||
|
# Or even better
|
||||||
|
with open("file.txt", "r") as f:
|
||||||
|
for line in f:
|
||||||
|
print(line)
|
||||||
|
|
||||||
|
# Even better
|
||||||
|
with open("newFile.txt", 'w') as f:
|
||||||
|
f.write("This is a new file\nI like it.\n")
|
||||||
|
|
||||||
|
# There are four modes of reading, r, w, a and r+
|
|
@ -0,0 +1,21 @@
|
||||||
|
"""
|
||||||
|
It is easier to reuse code and structure projects in multiple files.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# We can import our own code
|
||||||
|
|
||||||
|
funcs = __import__("03_functions")
|
||||||
|
|
||||||
|
print("\n\n")
|
||||||
|
funcs.fancy_func(3)
|
||||||
|
print("\n\n")
|
||||||
|
|
||||||
|
import pandas
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
print(np.pi)
|
||||||
|
|
||||||
|
from numpy import e
|
||||||
|
print(e)
|
||||||
|
|
||||||
|
# Libraries makes life easier, use pip for everything always
|
|
@ -0,0 +1,45 @@
|
||||||
|
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
|
||||||
|
Ornare suspendisse sed nisi lacus sed viverra tellus. Faucibus scelerisque eleifend donec pretium vulputate sapien. Mollis
|
||||||
|
nunc sed id semper. Quisque id diam vel quam elementum pulvinar etiam. Nibh sit amet commodo nulla facilisi nullam vehicula.
|
||||||
|
Porta lorem mollis aliquam ut porttitor. Senectus et netus et malesuada. Feugiat nibh sed pulvinar proin gravida hendrerit.
|
||||||
|
Sollicitudin aliquam ultrices sagittis orci a scelerisque purus semper eget. Arcu ac tortor dignissim convallis aenean et
|
||||||
|
tortor. Dictum non consectetur a erat nam at. Sagittis purus sit amet volutpat consequat mauris nunc. Nullam non nisi est
|
||||||
|
sit amet facilisis. Mi eget mauris pharetra et. Id consectetur purus ut faucibus pulvinar elementum integer enim. Enim
|
||||||
|
facilisis gravida neque convallis a cras semper auctor neque. Nunc vel risus commodo viverra maecenas accumsan lacus vel.
|
||||||
|
Consequat id porta nibh venenatis cras sed felis eget.
|
||||||
|
|
||||||
|
Mauris cursus mattis molestie a iaculis at. Enim nunc faucibus a pellentesque sit amet porttitor. Et ligula ullamcorper
|
||||||
|
malesuada proin libero nunc consequat. Pretium vulputate sapien nec sagittis aliquam malesuada bibendum arcu. Quam
|
||||||
|
viverra orci sagittis eu volutpat. Tellus in hac habitasse platea dictumst vestibulum rhoncus. Commodo ullamcorper a
|
||||||
|
lacus vestibulum. Mi eget mauris pharetra et ultrices. Quisque non tellus orci ac. Adipiscing bibendum est ultricies
|
||||||
|
integer quis auctor elit. Malesuada fames ac turpis egestas sed tempus urna et. Iaculis nunc sed augue lacus viverra
|
||||||
|
vitae congue eu consequat.
|
||||||
|
|
||||||
|
Sit amet nisl purus in mollis nunc sed id. Viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat. Elit
|
||||||
|
pellentesque habitant morbi tristique senectus et netus. Nec feugiat nisl pretium fusce id velit ut tortor. Et netus et
|
||||||
|
malesuada fames ac turpis egestas sed tempus. Sapien nec sagittis aliquam malesuada. Malesuada proin libero nunc
|
||||||
|
onsequat interdum varius sit amet. Sit amet porttitor eget dolor morbi non arcu risus. Id diam vel quam elementum.
|
||||||
|
Massa id neque aliquam vestibulum morbi blandit cursus risus at. Morbi leo urna molestie at elementum eu facilisis sed.
|
||||||
|
Odio euismod lacinia at quis. Et tortor consequat id porta nibh. Laoreet suspendisse interdum consectetur libero id
|
||||||
|
faucibus nisl tincidunt eget. Lacus suspendisse faucibus interdum posuere lorem ipsum dolor sit. Id nibh tortor id
|
||||||
|
aliquet lectus proin. Pretium nibh ipsum consequat nisl vel pretium lectus quam id. Vitae congue eu consequat ac felis
|
||||||
|
donec et odio. Mauris pellentesque pulvinar pellentesque habitant morbi tristique senectus et.
|
||||||
|
|
||||||
|
Vel eros donec ac odio tempor orci dapibus. Euismod lacinia at quis risus sed vulputate odio ut enim. Vel pharetra vel
|
||||||
|
turpis nunc eget. Justo nec ultrices dui sapien. Donec enim diam vulputate ut pharetra sit amet. Consectetur adipiscing
|
||||||
|
elit duis tristique. Ipsum nunc aliquet bibendum enim facilisis gravida neque convallis. Lorem mollis aliquam ut
|
||||||
|
porttitor leo a diam sollicitudin tempor. Integer vitae justo eget magna fermentum iaculis eu. Id faucibus nisl tincidunt
|
||||||
|
eget nullam non nisi. Tempus iaculis urna id volutpat lacus. Diam sit amet nisl suscipit adipiscing bibendum est.
|
||||||
|
Tellus orci ac auctor augue mauris. Accumsan sit amet nulla facilisi morbi tempus iaculis urna id. Fermentum iaculis eu
|
||||||
|
non diam phasellus vestibulum lorem sed. Iaculis urna id volutpat lacus laoreet non curabitur gravida. Id faucibus nisl
|
||||||
|
tincidunt eget.
|
||||||
|
|
||||||
|
Massa vitae tortor condimentum lacinia quis vel eros. Pulvinar pellentesque habitant morbi tristique senectus et netus.
|
||||||
|
Tincidunt dui ut ornare lectus sit amet est placerat in. Pellentesque elit eget gravida cum sociis. Malesuada fames ac
|
||||||
|
turpis egestas sed. Et odio pellentesque diam volutpat commodo sed egestas egestas fringilla. Augue lacus viverra vitae
|
||||||
|
congue eu consequat ac felis. Tempor orci dapibus ultrices in iaculis nunc sed augue. Odio ut enim blandit volutpat
|
||||||
|
maecenas volutpat blandit aliquam. Accumsan sit amet nulla facilisi morbi tempus. Habitant morbi tristique senectus
|
||||||
|
et netus et malesuada fames. Elementum facilisis leo vel fringilla est ullamcorper eget nulla facilisi. Mi tempus
|
||||||
|
imperdiet nulla malesuada pellentesque elit eget. Tristique sollicitudin nibh sit amet. Porttitor massa id neque aliquam
|
||||||
|
vestibulum morbi blandit cursus. Proin sed libero enim sed. Neque gravida in fermentum et sollicitudin ac orci.
|
||||||
|
Neque volutpat ac tincidunt vitae semper quis lectus nulla. A diam maecenas sed enim ut sem viverra.
|
|
@ -0,0 +1,6 @@
|
||||||
|
Kurstekst for introkurs i Python
|
||||||
|
|
||||||
|
|
||||||
|
Har du lyst til å lære å programmere i Python? Synes du ITGK-forelesningene går for sent, eller ønsker du å pusse opp glemte kunnskaper?
|
||||||
|
Da er dekke kurset for deg.
|
||||||
|
Kurset går gjennom språkets oppbygging fra kommentarer til overlagring av operatorer, ingen forkunnskaper kreves.
|
|
@ -0,0 +1,2 @@
|
||||||
|
This is a new file
|
||||||
|
I like it.
|
|
@ -0,0 +1,3 @@
|
||||||
|
asn1crypto<=0.24.0
|
||||||
|
astroid>=2.2.5
|
||||||
|
attrs
|
|
@ -0,0 +1 @@
|
||||||
|
pi
|
Loading…
Reference in New Issue