PythonTutorial

Aus Info-Theke
Zur Navigation springen Zur Suche springen


Using the Interpreter Interactive[Bearbeiten]

Calculator: 2*5.0+(3-2**17) % 12
Storing in a variable: a=2**31 ; len(str(a))
Using mathematical functions:
import math ; math.log10(2**63)
“unlimited” integers: 10**80
Method:
def fib(n) : return 1 if n <= 1 else fib(n-1) + fib(n-2)
Loop:
for x in range(10) : print('x: {:d} fib: {:d}'.format(x, fib(x)))

Important Types: list:[Bearbeiten]

List: mixed types, mutable
aList = [1, 2, 5, 'a string'] ; aList.append([3.0]) ; aList += ['x'] ; aList
Parts:
aList[3:] ; aList[:3] ; aList[1:3] ; b = [aList[2], aList[5]] ; b
Replace:
x=[1, 2, 3, 4, 5] ; x[0] = 'A2' ; x[1:3] = ['b2', 'c2'] ; x
Variables are references:
x=[1, 2, 3] ; y = x ; y[1] = 'x' ; x ; y
Copy a list “deeply”:
x=[1, 2, 3] ; y = x[:] ; y[1] = 'x' ; x ; y

Important Types: tuple, dict[Bearbeiten]

Tuple: immutable, different types
t = (1, 2, 'x') ; t
Dictionary (Hashtable): mutable
d = dict() ; d['abc'] = 22 ; d
d = { 22 : 'xy', 33 : 'z' } ; d[22] ; d
d.keys() ; d.values()
Iterator:
for key in d.keys(): 
     print('key: {:d} val: {:s}'.format(key, d[key]))