Commit 49c0d11d authored by Roger Kaeppeli's avatar Roger Kaeppeli

Add week 12

parent 02eb8580
x = [0,1,2]
y = x
y[2] = 666
print(x) # [0, 1, 666]
print(y) # [0, 1, 666]
import copy
x = [0,1,2]
y = copy.copy(x)
y[2] = 666
print(x) # [0, 1, 2]
print(y) # [0, 1, 666]
x = [0,1,[2,3]]
y = copy.copy(x)
y[2][0] = 666
print(x) # [0, 1, [666, 3]]
print(y) # [0, 1, [666, 3]]
x = [0,1,[2,3]]
y = copy.deepcopy(x)
y[2][0] = 666
print(x) # [0, 1, [2 , 3]]
print(y) # [0, 1, [666, 3]]
# Booleans: like in C++ but with capital T and F
True, False
# Integers
x = 1
# Floats: like in C++ with a dot (almost all platforms map Python floats
# to "double precision")
x = 1.
x = 1.e0
x = 1.E0
# Complex numbers
x = 1 + 1j
x = 1 + 1J
# Strings: with single or double quotes
x = 'string'
x = "string"
x = "Hello! I'm a string!"
x = 'Hi! I\'m "another" string!'
x = [1, 2, 3]
a = [val + 1 for val in x] # [2, 3, 4]
# can add a condition
b = [val + 1 for val in x if val != 2] # [2, 4]
y = dict(x=1, y=2, z=3)
a = {key + '_a': val + 1 for key, val in y.items() if val != 3}
# a == {'x_a': 2, 'y_a': 3}
def dec(f):
def inner():
print('Hello', end=' ')
f()
return inner
@dec # f = dec(f)
def f():
print('World')
f() # Hello World
x = dict(a=1, b=2, c='three')
x = {'a': 1, 'b': 2, 'c': 'three'}
# access via []
x['a'] == 1
# creating new entries
# any hashable type can be a key
x[1] = 4
# accessing keys, values or both
# order is not preserved
x.keys() # ['a', 'c', 1, 'b']
x.values() # [1, 'three', 4, 2]
x.items() # [('a', 1), (c, 'three'), (1, 4), ('b', 2)]
import sys
from numbers import Number
def func4posnuminput(x):
"""Function taking only numeric and positive input!"""
if ( isinstance(x, Number) ):
if ( x < 0 ): # note that this raise TypeError for Complex x!
raise ValueError
else:
raise TypeError
raise SyntaxError
X = [1,-1,2.71,-2.71,1j,abs(1.j),'1.9']
for x in X:
try:
func4posnuminput(x)
print("x = {:>5} raised no errors!".format(x))
except ValueError: # catch ValueError exception
print("x = {:>5} raised a ValueError".format(x))
except TypeError: # catch TypeError exception
print("x = {:>5} raised a TypeError".format(x))
except: # catch any other exception
# print the exception
print("Unexpected error:",sys.exc_info()[0])
raise # re-raise
import math
# open file and write some stuff
f = open("dummy.file",'w')
f.write("What I loose in sense I gain in poetry!\n")
f.write("e = {}\n".format(math.pi))
f.write("pi = {}\n".format(math.pi))
f.close()
# open file, read, check if it s closed and print it!
with open("dummy.file",'r') as f:
lines = f.readlines()
print("Is the file closed?", f.closed)
for line in lines:
print(line.strip()) # strip gets rid of \n's!
for item in [0, "a", 7, 1j]:
print(item)
for letter in "StRiNg":
print(letter)
for i in range(5):
print(i)
lst = ["Yamaha", "Suzuki", "Kawasaki", "Aprilia", "Ducati"]
# use enumerate below!!!
# for i in range(len(lst)):
# print(i, lst[i])
for (i, item) in enumerate(lst):
print(i, item)
import math
print("Table with default format:")
print("i", "PI**i", "PI**(2*i)", "PI**(3*i)")
for i in range(-5, +5+1):
print(i, math.pi**(i), math.pi**(2*i), math.pi**(3*i))
print(80*"#")
print("Table with some formatting:")
print("{:5s} {:15s} {:15s} {:15s}".format("i", "PI**i", "PI**(2*i)", \
"PI**(3*i)"))
for i in range(-5, +5+1):
print("{:5d} {:15g} {:15g} {:15g}".format(i,math.pi**( i), \
math.pi**(2*i), \
math.pi**(3*i)))
print(80*"#")
print("Table with more formatting:")
print("{:5s} {:15s} {:15s} {:15s}".format("i", "PI**i", "PI**(2*i)", \
"PI**(3*i)"))
for i in range(-5,+5+1):
print("{:5d} {:15.8e} {:15.8e} {:15.8e}".format(i,math.pi**( i), \
-math.pi**(2*i), \
-math.pi**(3*i)))
print(80*"#")
def fib(n):
"""Returns the nth Fibonacci number."""
a = 0
b = 1
for i in range(n):
tmp = a
a = a + b
b = tmp
return a
print("fib(5) =", fib(5))
def func(a, b=2, *args, c, d=4, e, **kwargs):
"""Function for illustration and docstring"""
print("### positional arguments ###################")
print(a)
print("### positional arguments with defaults #####")
print(b)
print("### variadic positional arguments ##########")
for (ia, a) in enumerate(args):
print(ia+1, a)
print("### keyword-only arguments #################")
print(c)
print(e)
print("### keyword-only arguments with defaults ###")
print(d)
print("### variadic pkeyword-only arguments #######")
for (ikwa, kwa) in enumerate(kwargs):
print(ikwa+1, kwa)
func("a", "b", "pa", "pb", "pc", c=5, e=6, kwarg1="kwarg1", kwarg2="kwarg2")
def apply(func, x):
return func(x)
x = apply(lambda z: z**2, 2.)
print(x)
def incr(x):
x += 1
x = 0
incr(x)
print(x)
def incr_first(x):
x[0] += 1
x = [0,1,2]
incr_first(x)
print(x)
x = 0
# if
if x < 0:
print("x is less than zero")
# if ... else
if x < 0:
print("x is less than zero")
else:
print("x is greater or equal zero")
# if ... elif ... else
if x < 0:
print("x is less than zero")
elif x > 0:
print("x is greater than zero")
else:
print("x is zero")
class A:
def __init__(self):
self.a = 1
def print_A(self):
print(self.a)
class B(A):
def __init__(self):
super().__init__() # self.a == 1
self.b = 2
def print_B(self):
print(self.b)
b = B()
b.print_A() # 1
b.print_B() # 2
# list is built-in
x = [0, 1, 2, 3, 3]
x[2] == 2 # access via [] index operator
x.insert(0, 5) # index, value
# x == [5, 0, 1, 2, 3, 3]
# remove by index - returns value
x.pop(0) # returns 5
# x == [0, 1, 2, 3, 3]
x = [0, 1, 2, 'three'] # can contain arbitrary types!
# access from the back with negative indices
x[-2] == 2
# adding lists concatenates them
x += [4, 5, 6] # x == [0, 1, 2, 'three', 4, 5, 6]
# slicing [start:end + 1]
x[1:4] == [1, 2, 'three']
# slicing [start: until end]
x[1:] == [1, 2, 'three', 4, 5, 6]
# slicing [beginning: until end - 1]
x[0:-1] == [0,1, 2, 'three', 4, 5]
# slicing with a stride [start:end + 1:step]
x[0:7:2] == x[::2] == [0, 2, 4, 6]
# reverse slicing
x[-1:0:-2] == [6, 4, 2]
x[::-2] == [6, 4, 2, 0]
class Point:
"""A simple two-dimensional Cartesian coordinates point"""
dim = 2 # static / class variable
def __init__(self, x, y):
"""Create point from two Cartesian coordinates"""
self._x = x # leading underscore for
self._y = y # private stuff convention
@staticmethod
def dimensions():
return Point.dim
@classmethod
def name(cls):
return cls.__name__
@property
def x(self):
"""The point's x coordinate"""
return self._x
@x.setter
def x(self, val):
self._x = val
@property
def y(self):
"""The point's y coordinate"""
return self._y
@y.setter
def y(self, val):
self._y = val
def scale(self, sx=1, sy=1):
"""Scale the point by a factors in x- and y-direction"""
self._x *= sx
self._y *= sy
def __add__(self, p):
"""Add to points"""
return Point(self._x + p._x, self._y + p._y)
def __str__(self):
"""Convert a point to string (e.g. for pretty-printing)"""
return "(" + str(self._x) + "," + str(self._y) + ")"
if __name__ == "__main__":
P1 = Point(1., 2.)
P2 = Point(0 , 7 )
print("P1 =", P1)
print("P2 =", P2)
P2.y = 2 # set P2.y to 2!
print("P2 =", P2)
print("P1 + P2 =", P1 + P2)
print(Point.dimensions())
x = 12/3 - 2 # this is a comment
y = "Hola"
z = 3.14 # another comment
if (y == "Hola" or z >= 3):
x = x + 2
y = y + " mundo!" # string concatenation
print(x)
year, month , day = 1943, 6, 15
hour, minute, second = 23, 6, 54
if 1900 < year < 2100 and 1 <= month <= 12 \
and 1 <= day <= 31 and 0 <= hour < 24 \
and 0 <= minute < 60 and 0 <= second < 60:
print("Looks like a valid date!")
5*7 # 35
5/2 # 2.5 floating point division
5//2 # 2 floor division
5 % 2 # 1 modulo operator
(17 - 3)/(4 - 5/3)
3**4 # power operator
1j**2
import math # import math. functions module
math.sqrt(2.)
math.sin(math.pi)
import random # import rand. numb. gen.
random.random()
import point # load the point module
# some more stuff for your application... functions, classes, ...
if __name__ == "__main__":
import sys
if ( len(sys.argv) > 1 ): # check number of command line arguments
P1 = point.Point(1., int(sys.argv[1])) # get P1's y coordinate from
# command line arguments
else:
P1 = point.Point(1., 2.)
P2 = point.Point(0., 7.)
P3 = P1 + P2
print(P3)
x = 0
while x < 7:
print("x =",x)
x += 1
x = 0
while x < 7:
if x == 2:
x += 1
continue # skip current iteration
if x == 6:
break # leave loop
print("x =",x)
x += 1
Markdown is supported
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