Filosofie:leesbare en compacte code
multi-paradigm: functioneel, OO, proceduraal
# dit is commentaar
10 / 3
3.3333333333333335
berekening = 5 * 6 + 3
print(berekening)
print(10 // 3) # gehele deling
print(10 ** 3) # machtsverheffing
33 3 1000
getal = input('Geef een getal: ')
print(float(getal) / 5) # type conversion; anders TypeError door operator /
Geef een getal: 3 0.6
langetekst = ('Lorem ipsum '
'omnis mundi creaturi')
print(langetekst)
woord = 'py' + 'thon' * 2
print(woord + '\n')
print("He didn't say " + '"hello"')
print(r'\n')
Lorem ipsum omnis mundi creaturi pythonthon He didn't say "hello" \n
#formatting
print('{1} and {0}'.format('spam', 'eggs'))
# include line ends using tripe-quotes
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to
woord = 'python'
print(len(woord)) # lengte van een string
# indexing and slicing
print('[1]: ' + woord[1])
print('[2:4]: ' + woord[2:4])
print('[-1]: ' + woord[-1])
print('[4:]: ' + woord[4:])
print('[:4]: ' + woord[:4])
6 [1]: y [2:4]: th [-1]: n [4:]: on [:4]: pyth
woord[0] = 'k' # strings zijn onveranderlijk ...
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-27-5dfbdb310324> in <module>() ----> 1 woord[0] = 'k' # string zijn onveranderlijk ... TypeError: 'str' object does not support item assignment
squares = [1, 4, 9, 16, 25]
# indexing and slicing
print(squares[0])
print(squares[-3:])
squares.append(36)
squares += [100, 121]
squares[6:8] = [49]
print(squares)
mycopy = squares[:] # shallow copy
print(len(squares))
1 [9, 16, 25] [1, 4, 9, 16, 25, 36, 49] 7
x = 5
if x < 0:
print('negatief')
elif x == 0:
print('nul')
else:
print('positief')
print(x)
positief 5
lijst = ['a', 'bb', 'ccc']
for woord in lijst:
print(woord, len(woord))
a 1 bb 2 ccc 3
for i in range(5):
print(i)
0 1 2 3 4
print(range(0, 10, 3)) # hmmm... eigenlijk is dit een object
print(list(range(0, 10, 3)))
range(0, 10, 3) [0, 3, 6, 9]
# na : is een statement vereist
# gebruik pass als je geen actie vereist (pass doet niets)
for i in range(5):
pass
def ask_ok(prompt, retries=4, reminder='Please try again!'): # default args
"""Asks the user for confirmation""" # documentatie
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)
ask_ok('OK to overwrite the file?', 2)
OK to overwrite the file?p Please try again! OK to overwrite the file?g Please try again! OK to overwrite the file?k
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-53-6ba11133dde6> in <module>() 12 print(reminder) 13 ---> 14 ask_ok('OK to overwrite the file?', 2) <ipython-input-53-6ba11133dde6> in ask_ok(prompt, retries, reminder) 9 retries = retries - 1 10 if retries < 0: ---> 11 raise ValueError('invalid user response') 12 print(reminder) 13 ValueError: invalid user response
ask_ok("is 't okee?", retries=0) # keyword arguments (steeds na postional args)
is 't okee?y
True
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print(fruits.count('apple'))
fruits.sort()
fruits.reverse()
print(fruits)
del fruits[1:2]
stack = [3, 4, 5]
stack.pop()
print(stack)
2 ['pear', 'orange', 'kiwi', 'banana', 'banana', 'apple', 'apple'] [3, 4]
# list comprehension
squares = [x**2 for x in range(10)]
print(squares)
vec = [-4, -2, 0, 2, 4]
print([x for x in vec if x >= 0])
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] [0, 2, 4]
resultaat = 25, 'Gent' # typisch voor heterogene data
print(resultaat[1]);
empty = ()
singleton = 'hello',
v = ([1, 2, 3], [3, 2, 1]) # tuples zijn onveranderlijk, hun elementen eventueel wel ...
print(len(singleton), len(v))
Gent 1 2
# de iterator van enumerate geeft tuples terug
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
0 tic 1 tac 2 toe
verzameling1 = {'A', 'B', 'C', 'D'}
verzameling2 = set('DAXYDA') # omzetten van lists, strings, ... naar een set
print(verzameling2)
print('A' in verzameling1) # snel opzoeken
print(verzameling1 | verzameling2) # unie
print(verzameling1 & verzameling2) # doorsnede
{'A', 'D', 'Y', 'X'} True {'C', 'X', 'Y', 'D', 'A', 'B'} {'A', 'D'}
# set comprehension
a = {x for x in 'abracadabra' if x not in 'abc'}
print(a)
{'r', 'd'}
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
if 'jack' in tel: # snel opzoeken
print(tel['jack'])
4098
tel2 = dict(sape=4139, guido=4127, jack=4098) # je kan ook een lijst van koppels gebruiken
del tel2['sape']
print(tel2)
for k, v in tel2.items():
print(k, v)
{'guido': 4127, 'jack': 4098} guido 4127 jack 4098
import math # importeren van de math module
print('pi is', math.pi)
pi is 3.141592653589793
import math as wiskunde
print('pi is', wiskunde.pi)
pi is 3.141592653589793
from math import cos, pi # from laat toe items, modules te importeren (en jokerteken *)
print('cos(pi) is', cos(pi))
cos(pi) is -1.0
import numpy as np
a = np.array([1, 2, 3])
print(a[0], type(a))
print(a)
print(np.arange(0, 3, 0.25)) # standard python kan geen ranges met kommagetallen genereren
1 <class 'numpy.ndarray'> [1 2 3] [0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. 2.25 2.5 2.75]
d = np.eye(3)
print(d)
e = np.full((3,3), 7)
print(e)
print(d*e)
[[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] [[7 7 7] [7 7 7] [7 7 7]] [[7. 0. 0.] [0. 7. 0.] [0. 0. 7.]]
import numpy as np
import matplotlib.pyplot as plt
# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)
# Plot the points using matplotlib
plt.plot(x, y)
plt.show()