Python-tutorial-2019

Aus Imaginärraum Wiki
Zur Navigation springen Zur Suche springen

Wird noch mit Syntaxhighlighting versehen sobald installiert.



# -*- coding: utf-8 -*-

#------------------------
# The python interpreter 
#------------------------

# From the console:
# > python               --> interactive python shell

print("Hello, World!")
exit()

# > python -c "Command"  --> execute a command directly
# > python <file.py>     --> process a python script
# > python -i <file.py>  --> go to interactive mode after processing a script  
# > python -m <module>   --> run a module directly

# Ctrl-C interrupts the program and returns to the shell

# This is a comment


#--------------------------
# Interactive calculations
#--------------------------

# Numeric constants:   1, 2.0, 3.4e5, 0xFF, 0b11110000
# Numerical operators: +, -, *, /, //, **, %
# Bit-wise operators:  &, |, ^, ~  
# Paratheses: ( )
# Last result: _  (interactive shell only)
# Number types: int, float, long, complex
# Long integer: 2**1000
# Floating point: 1.0, 1e3
# Complex numbers: c = complex(1,2), c = 1+2j
# Explicit casting: float(1), complex(5)
# Implicit casting:  2.0 * 5  (will result in 10.0)
# Integer division: 3/2 --> 1.5 ('true division'), 3//2 --> 1 ('classic division')
# Variable assignment:  =, +=, -=, *=, /=, //=, %=, **=
# built-in functions: abs, round


#-------------------
# Importing modules
#-------------------

import math
from math import exp, log, sqrt, sin, atanh
from math import *
import math as m
from math import sqrt as wurzel


#----------------- 
# Loops
#-----------------

# While-Do-Loop (head-controlled)
i = 1
while i<20:
    print( i )   # NOTE: indentation defines loop body block
    i += 1

# Syntax
while condition:
    command
    break     # abort looping immediately
    continue  # continue with next iteration immediately
else:
    command   # only executed if loop was NOT aborted with break
    
    
# There is no Do-While-Loop (tail-controlled) in python,
# but we can emulate one:
while 1:
    command
    if not condition:
        break


# For-loops
for i in range(5):
    print( i, sqrt(i) )

# Sytax
for i in mylist:
    command
    break
    continue
else:
    command
        
# For-loops really iterate over list-like objects
# (see below)


#----------------------------------
# Conditional operations, branches
#----------------------------------

# Comparison operators: ==, !=, >, >=, <, <=, is, in
# Boolean operators: and, or, not

for a in range(10):
    if a<5:
        comp = '<5'
    elif a==5:
        comp '==5'
    else:
        comp = '>5'
    print( a, comp )

    
# Single conditional commands do not require newlines:
if a>5: print('>5')


# Ternary operator
for a in range(10):
    print( a, '<5' if a<5 else '>=5' )
    
for a in range(10):
    print( a, '<5' if a<5 'a==5' if a==5 else '>5' )


#----------------
# Compound types
#---------------- 
  
tuple    # ordered, immutable
list     # ordered, mutable
dict     # unordered, associative
object

str        # ordered unicode text sequence, immutable
bytes      # ordered byte sequence, immutable
bytearray  # ordered byte sequence, mutable 


#------------ 
# Lists
#------------ 

a = [1,2,3,4,5]
b = [1, 2, 666, 0.001, 'Hello']
empty = []
empty.append(5)
empty.extend([6,7,8])  # Concatenation

c = a + b   # Concatenation
a * 3       # Duplication
a * 3 + b

a.append([11,22,33])  # Lists can contain lists
a.append(a)   # Can a list contain itself?
print( a )

len(a)
1 in a

# Indexing:
print( a[0], a[1], a[2] )
print( a[0:3] )  # 'slicing', excluding 3!!
print( a[-1] )   # last element
print( a[0:-1] )
print( a[0:] )   # stop index can be omitted (defaults to last element)
print( a[:-1] )  # start index can be omitted (defaults to first element)
print( a[:] )    # creates a copy
print( a[0:6:2] )  # every second item
print( a[::2]      

b = [1,2,[11,22,33]]
b[2]
b[2][0]

a[0] = 'overwritten'
a[0:3] = [0, 0, 0]  # assign multiple alements
a[0:3] = [123]      # no need for same length

del a[1]             # delete element at index 1
a.remove('thing')    # delete first occurence
a.insert(2,'buhuu')  # insert at position 2

for element in a:   # The for-loop really iterates over lists
    print(a)

print( list( range(10) )       # from 0..9
print( list( range(5,10) )     # from 5..9
print( list( range(10,50,5) )  # from 10 to 49 in steps of 5

# Often used for-loops:

for i in range(a):
    print( i )
    
for i,x in enumerate(a):
    print( i,x )
    
a = [1,2,3]
b = [4,5,6]
for x,y in zip(a,b):
    print( x,y )

# Sorting lists

a = [3,2,1]
a.sort()     # INPLACE! List is changed permanently.
sorted(a)    # Creates a sorted copy

a.reverse()  # INPLACE! Licst is changed permanently.
  
# List comprehension:
range(10)
squares = [x**2 for x in range(10)]
cubes = [x**2 for x in squares]
even_squares = [x**2 for x in range(10) if (x**2)%2]

# NOTE: Lists are NOT copied on assignment:
a = [1,2,3]
b = a       # b is just a reference to the same list
a[0] = 111
print( a,b )


a = [1,2,3]
b = [1,2,3]
a == b   # Test for same content
a is b   # Test or identical objects

b = a[:] # Creates a copy
a == b   # same content
a is b   # different opject

# Note: "Variables" in Python are rather references that refer to objects
id(a)  # Unique idetifier of the object refered to by a


# Some more operations on lists
sum(a)
min(a)
max(a)


#------------  
# Tuples
#------------

# Like lists, but immutable (read-only)
t = (1,2,3)
t[0]
t[0] = 666  # Error

# Tuple assignment:
x,y,z = (1,2,3)
x,y,z = 1,2,3    # parantheses not needed
x,y = y,x

# Packing/unpacking
a = 1,2,3
x,y,z = a

# Can be used to return multiple values from a function, eg.
def first_and_last(x):
    return x[0],x[-1]

first, last = first_and_last(x)

# To modify tuples, cast them to lists
list(a)

# Sometimes we need tupels with a single element
t = (1, )

  
#-----------------
# Strings (text)
#-----------------

# Like lists, only characters, immutable (read-only)
# some additional text-related functions
s = "Hello"
s2 = 'World'  # No difference between ' and "

german = 'Ätschebätsch'  # In Python3 strings are unicode by default

# Escape symbols: \n \t \" \' \xNN
se = "\"Hello!\"n"

# Indexing like lists
s[0:2]
s[0] = 'B'  # Error

h = s + ', ' + s2  # Concatenation
g = (s + ' ') * 5

g.split()  # Whitespaces
h.split(',')
'-'.join(['a','b','c'])  # Opposite of split
  
h.count('l')
h.find('World')
'World' in h

h.startswith('Hello')

# And many more. See http://docs.python.org/2/library/stdtypes.html#string-methods

# Multiline strings (aka triple-quoted-strings)
"""This string can span multiple lines.
We can use ' and ", and escape sequences 
like \n are not expanded (\" and \' are, though)"""

# String formatting:
for i in range(20):
    print( "%d\t%.3f" % (i, sqrt(i)) )  # old-style printf

for i in range(20):
    print( "{0:d}\t{1:.3f}".format(i, sqrt(i)) )  # new-style



#-----------------
# Byte sequences 
#-----------------

# Like strings, but can only contain 8-bit integer characters (0..255)
# or ASCII text characters (0..127). 

b = b'hello'     # prepend literals with b
b'hällo'         # Error
b'\xF0\xF1\xF2'  # use escape sequences for values > 127.

bytes([1,2,3])  # construct from list
bytes(5)        # --> byte sequence of 5 zeros
# BEWARE! In Python2: bytes(5) --> '5'

# Bytes are immutable. For mutable bytes sequences use bytearrays
by = bytes([1,2,3])
by[0] = 0   # Error
ba = bytearray([1,2,3])
ba[0] = 0   # Ok
  
# Byte sequences support mostly the same operations as text strings

# Encoding/decoding text strings
s = 'Wörld'
print(s)
b = s.encode('utf-8')    # encode: unicode text --> byte-sequence
print(b)
print(b.decode('utf-8')  # decode: byte-sequence --> unicode text


#--------------
# Dictionaries  
#--------------

# Unordered associative array
# Key-value pairs
d = {'first': 1, 'second': 2, 'third': 3, 0:123, 1:[11,22,33], 2:sin }
d[0]
d['first']

d['none']    # Error
d.has_key('none')  # XXX Has been removed in Python3
'none' in d
d.get('none', 0)  # returns default if key not found

d.keys()
d.values()
d.items()

# Dictionary comprehension
names = ['Thomas', 'Sabine', 'Fridolin']
lengths = { n:len(n) for n in names }


#---------------
# Functions
#---------------

def fibo(n):
    a, b = 0, 1
    while a < n:
        print(a, end='')
        a, b = b, a+b
fibo(1000)

def fibolist(n):
    f = []
    a, b = 0, 1
    while a < n:
        f.append(a)
        a, b = b, a+b
    return f
fibolist(1000)

# One-line function definition
func = lambda x: x**2 + 1

# identical to
def func(x):
  return x**2 + 1

# Docstrings
def nothing():
    """This function does nothing"""
    pass

help(nothing)
  

#-----------------  
# File access
#-----------------

f = open('input.dat')  # default is reading
f.read()
f.read()  # --> nothing, end of file
f.seek(0)
d = f.read()
f.seek(0)
lines = f.readlines()
data = [ line.split()  for line in lines if not line.startswith('#') ]
f.close()

f = open('output.dat','w')  # open for writing
f.write('#Some cubes\n')
for i in range(100):
    f.write( str(i) + '\t' + str(i**3) + '\n' )
f.close()

# HINT: Use append mode and buffer=0 when writing measurement files:
f = open('out.dat','a', 0)

# Binary files
f.write(b'123')  # Error
f = open('out.dat', 'r+b')   # 'r+' opens the file for both reading and writing
f.write(b'123')
f.seek(0)
f.read()   # --> returns byte sequence, not text


#------------------------------------
# Exceptions
#------------------------------------



#------------------------------------
# Numpy: Fast Numerical calculations
#------------------------------------

from numpy import *

# Adds a new datatype: array, 
# Overloads all mathematical operators and functions for use with arrays

# Pure python way:
N = 100
x = [ float(i)/N for i in range(N) ]
y = [ sin(2*pi*i) for i in x ]

# Numpy
x = arange(0, 1, 1./N)
y = sin(2*pi*x)  # Default: All operations work element-wise

y2 = cos(2*pi*x)
y3 = y + y2 + 1
y4 = y**2 + y2**2

y.max()
y.min()
y.mean()
y.sum()

y.argmin(), y.argmax()

# Creating arrays
n = array( [2, 4, 6, 8] )
a = arange(N)
z = zeros(N)
o = ones(N)
e = empty(N)
f = full(N, 1.23)

# Take care of datatypes!
arange(5)
arange(5.)

# Better use explicit data type:
arange(5, dtype=complex)

# For a list of types see
# http://docs.scipy.org/doc/numpy/user/basics.types.html

#Convert to a different type
a.astype(uint8)

# Multi-dimensional arrays
a2 = array( [[0, 1, 2], [1, 2, 3], [2, 3, 4], [5, 6, 7]] )
a2.shape
a2.transpose()  # transposed copy

a3 = zeros( (3,3,3) )

# Access and slicing like lists
x[0]
y[0:N:2]  # NOTE: Array slices are NOT copied ('view')

yy = y.copy() # Need to copy explicitly

a2[0, 0]     # rows, columns (or y, x coordinates), axis 0,1
a3[0, 0, 0]  # outer, middle, inner axis, axis numbers 0, 1 ,2
a3[:, 1, :]  

# Default: Last axis is contiguous in memory ('C'-order)
# Can be changed to Fortran.order:
f = ones( (5,5), order='F' )
f2 = a3.asfortranarray()

# Operations

a = array([1,2,3])
b = array([2,2,2])

a*b + 1  # Element-wise 
dot(a,b) # Scalar/Matrix product

# Boolean indexing
a = arange(10) - 5
a>0  # Comparison returns array of bools
a[a>0] = 1  # bool arrays can be used for indexing

all(a>0)  # True for all entries?
any(a>0)  # true for at least one entry?

# Ascii files
a = loadtxt('input.dat')
savetxt('output.dat', a, fmt='%.3f')


#------------
# Matplotlib
#------------

from numpy import *
N = 100
x = arange(0, 1, 1./N)
y = sin(2*pi*x)
y2 = cos(2*pi*x)

import matplotlib.pyplot as pyplot
pyplot.interactive(1)

pyplot.plot(x, y, 'b-')
pyplot.plot(x, y2, 'r-')
pyplot.show()

pyplot.clf()
pyplot.close()