BlahBlah

[1]:
i = 666
[2]:
print(i)
666
[3]:
print(type(i))
<class 'int'>
[4]:
j = 42
[5]:
def f():
    print('hallo')
[6]:
f()
hallo
[7]:
print(type(f))
<class 'function'>
[8]:
class Square:
    def __init__(self, kantenlaenge):
        self.kantenlaenge = kantenlaenge
    def area(self):
        return self.kantenlaenge ** 2
[9]:
q = Square(10)
q.area()
[9]:
100
[10]:
s = 'mississippi'
print(type(s))
<class 'str'>
[11]:
s.count('ss')
[11]:
2
[12]:
s.find('ss')
[12]:
2

Interactive

[13]:
i = 0
summe = 0
while i < 100:
    summe += i
    i += 1
print(summe)
4950

For Beginners

[14]:
for element in range(0,5):
    print(element)
0
1
2
3
4

Not For Beginners?

[15]:
i = 666
[16]:
type(i)
[16]:
int
[17]:
i = ['eins', 1, 1.0]
[18]:
type(i)
[18]:
list
[19]:
a = 42
b = '666'
[20]:
try:
    if a < b:
        print('jo eh')
except Exception as e:
    print(type(e), e)
<class 'TypeError'> '<' not supported between instances of 'int' and 'str'

Strings, 1st Explanation

[21]:
s = 'abc'
s
[21]:
'abc'
[22]:
s = "abc"
s
[22]:
'abc'
[23]:
s = 'ab"cd'
s
[23]:
'ab"cd'
[24]:
s = "ab'cd"
s
[24]:
"ab'cd"
[25]:
print(s)
ab'cd
[26]:
try:
    s = 'abc
except Exception as e:
    print(type(e), e)
  File "/tmp/ipykernel_101004/2437887948.py", line 2
    s = 'abc
            ^
SyntaxError: EOL while scanning string literal

Datatypes

Integers

[ ]:
i = 666   # decimal
[ ]:
i
[ ]:
i = 0x10  # hexadecimal
[ ]:
i
[ ]:
i = 0b11
[ ]:
i
[27]:
i = 1* 2**0  + 1* 2**1
[28]:
i
[28]:
3
[29]:
i = 0b10100
[30]:
i
[30]:
20
[31]:
i = 0*2**0 + 0*2**1 + 1*2**2 + 0*2**3 + 1*2**4
[32]:
i
[32]:
20
[33]:
i = 0o755
i
[33]:
493
[34]:
i = 0b1111111111111111111111111111111111111111111111111111111111111111
i
[34]:
18446744073709551615
[35]:
bin(i)
[35]:
'0b1111111111111111111111111111111111111111111111111111111111111111'
[36]:
i += 1
bin(i)
[36]:
'0b10000000000000000000000000000000000000000000000000000000000000000'
[37]:
2**64-1
[37]:
18446744073709551615
[38]:
2**64
[38]:
18446744073709551616
[39]:
bin(2**64)
[39]:
'0b10000000000000000000000000000000000000000000000000000000000000000'
[40]:
2**100
[40]:
1267650600228229401496703205376
[41]:
2**100 + 5
[41]:
1267650600228229401496703205381
[42]:
2**1000
[42]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Operators

[43]:
1 < 2
[43]:
True
[44]:
1 <= 2
[44]:
True
[45]:
2 <= 2
[45]:
True
[46]:
1 > 2
[46]:
False
[47]:
1 >= 2
[47]:
False
[48]:
try:
    1 = 2
except Exception as e:
    print(type(e), e)
  File "/tmp/ipykernel_101004/735611673.py", line 2
    1 = 2
    ^
SyntaxError: cannot assign to literal

[ ]:
1 == 2
[ ]:
1 != 2

Integer Numbers: Arithmetic

[ ]:
1 + 2
[ ]:
1 - 2
[ ]:
3/2
[ ]:
3//2
[ ]:
5//2
[ ]:
5//3
[ ]:
round(1.5)
[49]:
round(1.3)
[49]:
1
[50]:
help(round)
Help on built-in function round in module builtins:

round(number, ndigits=None)
    Round a number to a given precision in decimal digits.

    The return value is an integer if ndigits is omitted or None.  Otherwise
    the return value has the same type as the number.  ndigits may be negative.

[51]:
import math

math.floor(2.1)
[51]:
2
[52]:
math.ceil(2.1)
[52]:
3
[53]:
5 % 2
[53]:
1
[54]:
7%4
[54]:
3
[55]:
7 % 2
[55]:
1
[56]:
def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False
[57]:
is_even(7)
[57]:
False
[58]:
is_even(4)
[58]:
True
[59]:
sum([1,2,3])
[59]:
6
[60]:
import statistics
[61]:
statistics.mean([1,2,3])
[61]:
2
[62]:
2^3    # exclusive or
[62]:
1
[63]:
bin(0b101 & 0b100)
[63]:
'0b100'
[64]:
bin(0b101 | 0b100)
[64]:
'0b101'
[65]:
bin(0b101 ^ 0b100)
[65]:
'0b1'
[66]:
2**3
[66]:
8
[67]:
register_status = 0b1001000
[68]:
mask = 0b00001000
[69]:
bin(register_status & mask)
[69]:
'0b1000'
[70]:
if register_status & mask:
    print('hey, da liegt strom an!')
hey, da liegt strom an!
[71]:
def liegt_strom_an(register_status):
    if register_status & 0b1000:
        return True
    return False
[72]:
liegt_strom_an(0b00111110)
[72]:
True
[73]:
i = 42
i = i+1
i
[73]:
43
[74]:
i += 1
i
[74]:
44
[75]:
i += 52
[76]:
i
[76]:
96

Operator Precedence

[77]:
1 + 2 * 3
[77]:
7
[78]:
(1 + 2) * 3
[78]:
9
[79]:
2 * 3 / 4
[79]:
1.5
[80]:
2 * 3 % 2
[80]:
0
[81]:
(2 * 3) % 2
[81]:
0
[82]:
2 * 3 ** 2
[82]:
18
[83]:
2 * (2 ** 3)
[83]:
16

Floating Point Numbers

[84]:
2/3
[84]:
0.6666666666666666

DONT EVER DO THIS:

[85]:
2/3 == 100/150
[85]:
True

Datatype Conversions

[86]:
s = '666'
[87]:
i = int(s)
[88]:
i
[88]:
666
[89]:
i = 42
[90]:
str(i)
[90]:
'42'
[91]:
float('666.42')
[91]:
666.42
[92]:
int(666.42)
[92]:
666
[93]:
float(666)
[93]:
666.0
[94]:
int('10', 16)
[94]:
16
[95]:
int('deadbeef', 16)
[95]:
3735928559

Boolean

[96]:
not (1<2)
[96]:
False
[97]:
not 1<2
[97]:
False
[98]:
not 1
[98]:
False
[99]:
not 0
[99]:
True
[100]:
True or False
[100]:
True
[101]:
True and False
[101]:
False
[102]:
False or True
[102]:
True
[103]:
False or False
[103]:
False
[104]:
False or (True and True)
[104]:
True
[105]:
i = 666
[106]:
if i > 0 and i < 1000:
    print('eh im range')
eh im range
[107]:
s = 'grosses dokument mit doktor irgendwo drin'
if s.find('doktor') != -1:
    print('jawui ein akademiker')
jawui ein akademiker

More About Strings

[108]:
s = 'abc'
print(s)
abc
[109]:
s = "abc"
print(s)
abc
[110]:
s = 'ab"cd'
print(s)
ab"cd
[111]:
s = "ab'cd"
print(s)
ab'cd
[112]:
s = 'abc\ndef'
print(s)
abc
def
[113]:
s = 'abc\tdef'
print(s)
abc     def
[114]:
s = 'ab\'cd'
print(s)
ab'cd
[115]:
s = 'abc"def\'geh'
print(s)
abc"def'geh
[116]:
s = 'C:\some\name'
print(s)
C:\some
ame
[117]:
s = 'C:\some\\name'
print(s)
C:\some\name
[118]:
s = r'C:\some\name'
print(s)
C:\some\name

Multiline strings

[119]:
s = '''
eine zeile
noch eine zeile
und noch eine
und jetzt die letzte
'''
print(s)

eine zeile
noch eine zeile
und noch eine
und jetzt die letzte

[120]:
s = 'abc'        'def'
print(s)
abcdef

Docstrings

[121]:
def summe(a, b):
    '''Diese hochkomplexe Algorithmus verendet Euler'sche woswasi
    was man hier noch fuer einen Bullshit dokumentiern koennte,
    und noch 200 zeilen hier
    '''
    return a+b
[122]:
s = summe(1,2)
print(s)
3
[123]:
type(summe)
[123]:
function
[124]:
summe.__doc__
[124]:
"Diese hochkomplexe Algorithmus verendet Euler'sche woswasi\n    was man hier noch fuer einen Bullshit dokumentiern koennte,\n    und noch 200 zeilen hier\n    "
[125]:
help(summe)
Help on function summe in module __main__:

summe(a, b)
    Diese hochkomplexe Algorithmus verendet Euler'sche woswasi
    was man hier noch fuer einen Bullshit dokumentiern koennte,
    und noch 200 zeilen hier

[126]:
import statistics
[127]:
help(statistics)
Help on module statistics:

NAME
    statistics - Basic statistics module.

MODULE REFERENCE
    https://docs.python.org/3.9/library/statistics

    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides functions for calculating statistics of data, including
    averages, variance, and standard deviation.

    Calculating averages
    --------------------

    ==================  ==================================================
    Function            Description
    ==================  ==================================================
    mean                Arithmetic mean (average) of data.
    fmean               Fast, floating point arithmetic mean.
    geometric_mean      Geometric mean of data.
    harmonic_mean       Harmonic mean of data.
    median              Median (middle value) of data.
    median_low          Low median of data.
    median_high         High median of data.
    median_grouped      Median, or 50th percentile, of grouped data.
    mode                Mode (most common value) of data.
    multimode           List of modes (most common values of data).
    quantiles           Divide data into intervals with equal probability.
    ==================  ==================================================

    Calculate the arithmetic mean ("the average") of data:

    >>> mean([-1.0, 2.5, 3.25, 5.75])
    2.625


    Calculate the standard median of discrete data:

    >>> median([2, 3, 4, 5])
    3.5


    Calculate the median, or 50th percentile, of data grouped into class intervals
    centred on the data values provided. E.g. if your data points are rounded to
    the nearest whole number:

    >>> median_grouped([2, 2, 3, 3, 3, 4])  #doctest: +ELLIPSIS
    2.8333333333...

    This should be interpreted in this way: you have two data points in the class
    interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in
    the class interval 3.5-4.5. The median of these data points is 2.8333...


    Calculating variability or spread
    ---------------------------------

    ==================  =============================================
    Function            Description
    ==================  =============================================
    pvariance           Population variance of data.
    variance            Sample variance of data.
    pstdev              Population standard deviation of data.
    stdev               Sample standard deviation of data.
    ==================  =============================================

    Calculate the standard deviation of sample data:

    >>> stdev([2.5, 3.25, 5.5, 11.25, 11.75])  #doctest: +ELLIPSIS
    4.38961843444...

    If you have previously calculated the mean, you can pass it as the optional
    second argument to the four "spread" functions to avoid recalculating it:

    >>> data = [1, 2, 2, 4, 4, 4, 5, 6]
    >>> mu = mean(data)
    >>> pvariance(data, mu)
    2.5


    Exceptions
    ----------

    A single exception is defined: StatisticsError is a subclass of ValueError.

CLASSES
    builtins.ValueError(builtins.Exception)
        StatisticsError
    builtins.object
        NormalDist

    class NormalDist(builtins.object)
     |  NormalDist(mu=0.0, sigma=1.0)
     |
     |  Normal distribution of a random variable
     |
     |  Methods defined here:
     |
     |  __add__(x1, x2)
     |      Add a constant or another NormalDist instance.
     |
     |      If *other* is a constant, translate mu by the constant,
     |      leaving sigma unchanged.
     |
     |      If *other* is a NormalDist, add both the means and the variances.
     |      Mathematically, this works only if the two distributions are
     |      independent or if they are jointly normally distributed.
     |
     |  __eq__(x1, x2)
     |      Two NormalDist objects are equal if their mu and sigma are both equal.
     |
     |  __hash__(self)
     |      NormalDist objects hash equal if their mu and sigma are both equal.
     |
     |  __init__(self, mu=0.0, sigma=1.0)
     |      NormalDist where mu is the mean and sigma is the standard deviation.
     |
     |  __mul__(x1, x2)
     |      Multiply both mu and sigma by a constant.
     |
     |      Used for rescaling, perhaps to change measurement units.
     |      Sigma is scaled with the absolute value of the constant.
     |
     |  __neg__(x1)
     |      Negates mu while keeping sigma the same.
     |
     |  __pos__(x1)
     |      Return a copy of the instance.
     |
     |  __radd__ = __add__(x1, x2)
     |
     |  __repr__(self)
     |      Return repr(self).
     |
     |  __rmul__ = __mul__(x1, x2)
     |
     |  __rsub__(x1, x2)
     |      Subtract a NormalDist from a constant or another NormalDist.
     |
     |  __sub__(x1, x2)
     |      Subtract a constant or another NormalDist instance.
     |
     |      If *other* is a constant, translate by the constant mu,
     |      leaving sigma unchanged.
     |
     |      If *other* is a NormalDist, subtract the means and add the variances.
     |      Mathematically, this works only if the two distributions are
     |      independent or if they are jointly normally distributed.
     |
     |  __truediv__(x1, x2)
     |      Divide both mu and sigma by a constant.
     |
     |      Used for rescaling, perhaps to change measurement units.
     |      Sigma is scaled with the absolute value of the constant.
     |
     |  cdf(self, x)
     |      Cumulative distribution function.  P(X <= x)
     |
     |  inv_cdf(self, p)
     |      Inverse cumulative distribution function.  x : P(X <= x) = p
     |
     |      Finds the value of the random variable such that the probability of
     |      the variable being less than or equal to that value equals the given
     |      probability.
     |
     |      This function is also called the percent point function or quantile
     |      function.
     |
     |  overlap(self, other)
     |      Compute the overlapping coefficient (OVL) between two normal distributions.
     |
     |      Measures the agreement between two normal probability distributions.
     |      Returns a value between 0.0 and 1.0 giving the overlapping area in
     |      the two underlying probability density functions.
     |
     |          >>> N1 = NormalDist(2.4, 1.6)
     |          >>> N2 = NormalDist(3.2, 2.0)
     |          >>> N1.overlap(N2)
     |          0.8035050657330205
     |
     |  pdf(self, x)
     |      Probability density function.  P(x <= X < x+dx) / dx
     |
     |  quantiles(self, n=4)
     |      Divide into *n* continuous intervals with equal probability.
     |
     |      Returns a list of (n - 1) cut points separating the intervals.
     |
     |      Set *n* to 4 for quartiles (the default).  Set *n* to 10 for deciles.
     |      Set *n* to 100 for percentiles which gives the 99 cuts points that
     |      separate the normal distribution in to 100 equal sized groups.
     |
     |  samples(self, n, *, seed=None)
     |      Generate *n* samples for a given mean and standard deviation.
     |
     |  zscore(self, x)
     |      Compute the Standard Score.  (x - mean) / stdev
     |
     |      Describes *x* in terms of the number of standard deviations
     |      above or below the mean of the normal distribution.
     |
     |  ----------------------------------------------------------------------
     |  Class methods defined here:
     |
     |  from_samples(data) from builtins.type
     |      Make a normal distribution instance from sample data.
     |
     |  ----------------------------------------------------------------------
     |  Readonly properties defined here:
     |
     |  mean
     |      Arithmetic mean of the normal distribution.
     |
     |  median
     |      Return the median of the normal distribution
     |
     |  mode
     |      Return the mode of the normal distribution
     |
     |      The mode is the value x where which the probability density
     |      function (pdf) takes its maximum value.
     |
     |  stdev
     |      Standard deviation of the normal distribution.
     |
     |  variance
     |      Square of the standard deviation.

    class StatisticsError(builtins.ValueError)
     |  Method resolution order:
     |      StatisticsError
     |      builtins.ValueError
     |      builtins.Exception
     |      builtins.BaseException
     |      builtins.object
     |
     |  Data descriptors defined here:
     |
     |  __weakref__
     |      list of weak references to the object (if defined)
     |
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.ValueError:
     |
     |  __init__(self, /, *args, **kwargs)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |
     |  ----------------------------------------------------------------------
     |  Static methods inherited from builtins.ValueError:
     |
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.
     |
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.BaseException:
     |
     |  __delattr__(self, name, /)
     |      Implement delattr(self, name).
     |
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |
     |  __reduce__(...)
     |      Helper for pickle.
     |
     |  __repr__(self, /)
     |      Return repr(self).
     |
     |  __setattr__(self, name, value, /)
     |      Implement setattr(self, name, value).
     |
     |  __setstate__(...)
     |
     |  __str__(self, /)
     |      Return str(self).
     |
     |  with_traceback(...)
     |      Exception.with_traceback(tb) --
     |      set self.__traceback__ to tb and return self.
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from builtins.BaseException:
     |
     |  __cause__
     |      exception cause
     |
     |  __context__
     |      exception context
     |
     |  __dict__
     |
     |  __suppress_context__
     |
     |  __traceback__
     |
     |  args

FUNCTIONS
    fmean(data)
        Convert data to floats and compute the arithmetic mean.

        This runs faster than the mean() function and it always returns a float.
        If the input dataset is empty, it raises a StatisticsError.

        >>> fmean([3.5, 4.0, 5.25])
        4.25

    geometric_mean(data)
        Convert data to floats and compute the geometric mean.

        Raises a StatisticsError if the input dataset is empty,
        if it contains a zero, or if it contains a negative value.

        No special efforts are made to achieve exact results.
        (However, this may change in the future.)

        >>> round(geometric_mean([54, 24, 36]), 9)
        36.0

    harmonic_mean(data)
        Return the harmonic mean of data.

        The harmonic mean, sometimes called the subcontrary mean, is the
        reciprocal of the arithmetic mean of the reciprocals of the data,
        and is often appropriate when averaging quantities which are rates
        or ratios, for example speeds. Example:

        Suppose an investor purchases an equal value of shares in each of
        three companies, with P/E (price/earning) ratios of 2.5, 3 and 10.
        What is the average P/E ratio for the investor's portfolio?

        >>> harmonic_mean([2.5, 3, 10])  # For an equal investment portfolio.
        3.6

        Using the arithmetic mean would give an average of about 5.167, which
        is too high.

        If ``data`` is empty, or any element is less than zero,
        ``harmonic_mean`` will raise ``StatisticsError``.

    mean(data)
        Return the sample arithmetic mean of data.

        >>> mean([1, 2, 3, 4, 4])
        2.8

        >>> from fractions import Fraction as F
        >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
        Fraction(13, 21)

        >>> from decimal import Decimal as D
        >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
        Decimal('0.5625')

        If ``data`` is empty, StatisticsError will be raised.

    median(data)
        Return the median (middle value) of numeric data.

        When the number of data points is odd, return the middle data point.
        When the number of data points is even, the median is interpolated by
        taking the average of the two middle values:

        >>> median([1, 3, 5])
        3
        >>> median([1, 3, 5, 7])
        4.0

    median_grouped(data, interval=1)
        Return the 50th percentile (median) of grouped continuous data.

        >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
        3.7
        >>> median_grouped([52, 52, 53, 54])
        52.5

        This calculates the median as the 50th percentile, and should be
        used when your data is continuous and grouped. In the above example,
        the values 1, 2, 3, etc. actually represent the midpoint of classes
        0.5-1.5, 1.5-2.5, 2.5-3.5, etc. The middle value falls somewhere in
        class 3.5-4.5, and interpolation is used to estimate it.

        Optional argument ``interval`` represents the class interval, and
        defaults to 1. Changing the class interval naturally will change the
        interpolated 50th percentile value:

        >>> median_grouped([1, 3, 3, 5, 7], interval=1)
        3.25
        >>> median_grouped([1, 3, 3, 5, 7], interval=2)
        3.5

        This function does not check whether the data points are at least
        ``interval`` apart.

    median_high(data)
        Return the high median of data.

        When the number of data points is odd, the middle value is returned.
        When it is even, the larger of the two middle values is returned.

        >>> median_high([1, 3, 5])
        3
        >>> median_high([1, 3, 5, 7])
        5

    median_low(data)
        Return the low median of numeric data.

        When the number of data points is odd, the middle value is returned.
        When it is even, the smaller of the two middle values is returned.

        >>> median_low([1, 3, 5])
        3
        >>> median_low([1, 3, 5, 7])
        3

    mode(data)
        Return the most common data point from discrete or nominal data.

        ``mode`` assumes discrete data, and returns a single value. This is the
        standard treatment of the mode as commonly taught in schools:

            >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
            3

        This also works with nominal (non-numeric) data:

            >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
            'red'

        If there are multiple modes with same frequency, return the first one
        encountered:

            >>> mode(['red', 'red', 'green', 'blue', 'blue'])
            'red'

        If *data* is empty, ``mode``, raises StatisticsError.

    multimode(data)
        Return a list of the most frequently occurring values.

        Will return more than one result if there are multiple modes
        or an empty list if *data* is empty.

        >>> multimode('aabbbbbbbbcc')
        ['b']
        >>> multimode('aabbbbccddddeeffffgg')
        ['b', 'd', 'f']
        >>> multimode('')
        []

    pstdev(data, mu=None)
        Return the square root of the population variance.

        See ``pvariance`` for arguments and other details.

        >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
        0.986893273527251

    pvariance(data, mu=None)
        Return the population variance of ``data``.

        data should be a sequence or iterable of Real-valued numbers, with at least one
        value. The optional argument mu, if given, should be the mean of
        the data. If it is missing or None, the mean is automatically calculated.

        Use this function to calculate the variance from the entire population.
        To estimate the variance from a sample, the ``variance`` function is
        usually a better choice.

        Examples:

        >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
        >>> pvariance(data)
        1.25

        If you have already calculated the mean of the data, you can pass it as
        the optional second argument to avoid recalculating it:

        >>> mu = mean(data)
        >>> pvariance(data, mu)
        1.25

        Decimals and Fractions are supported:

        >>> from decimal import Decimal as D
        >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
        Decimal('24.815')

        >>> from fractions import Fraction as F
        >>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
        Fraction(13, 72)

    quantiles(data, *, n=4, method='exclusive')
        Divide *data* into *n* continuous intervals with equal probability.

        Returns a list of (n - 1) cut points separating the intervals.

        Set *n* to 4 for quartiles (the default).  Set *n* to 10 for deciles.
        Set *n* to 100 for percentiles which gives the 99 cuts points that
        separate *data* in to 100 equal sized groups.

        The *data* can be any iterable containing sample.
        The cut points are linearly interpolated between data points.

        If *method* is set to *inclusive*, *data* is treated as population
        data.  The minimum value is treated as the 0th percentile and the
        maximum value is treated as the 100th percentile.

    stdev(data, xbar=None)
        Return the square root of the sample variance.

        See ``variance`` for arguments and other details.

        >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
        1.0810874155219827

    variance(data, xbar=None)
        Return the sample variance of data.

        data should be an iterable of Real-valued numbers, with at least two
        values. The optional argument xbar, if given, should be the mean of
        the data. If it is missing or None, the mean is automatically calculated.

        Use this function when your data is a sample from a population. To
        calculate the variance from the entire population, see ``pvariance``.

        Examples:

        >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
        >>> variance(data)
        1.3720238095238095

        If you have already calculated the mean of your data, you can pass it as
        the optional second argument ``xbar`` to avoid recalculating it:

        >>> m = mean(data)
        >>> variance(data, m)
        1.3720238095238095

        This function does not check that ``xbar`` is actually the mean of
        ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
        impossible results.

        Decimals and Fractions are supported:

        >>> from decimal import Decimal as D
        >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
        Decimal('31.01875')

        >>> from fractions import Fraction as F
        >>> variance([F(1, 6), F(1, 2), F(5, 3)])
        Fraction(67, 108)

DATA
    __all__ = ['NormalDist', 'StatisticsError', 'fmean', 'geometric_mean',...

FILE
    /usr/lib64/python3.9/statistics.py


[128]:
dir(summe)
[128]:
['__annotations__',
 '__call__',
 '__class__',
 '__closure__',
 '__code__',
 '__defaults__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__get__',
 '__getattribute__',
 '__globals__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__kwdefaults__',
 '__le__',
 '__lt__',
 '__module__',
 '__name__',
 '__ne__',
 '__new__',
 '__qualname__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__']
[129]:
summe(100, 200)
[129]:
300
[130]:
summe.__call__(100, 200)
[130]:
300
[131]:
i = 666
[132]:
dir(i)
[132]:
['__abs__',
 '__add__',
 '__and__',
 '__bool__',
 '__ceil__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__index__',
 '__init__',
 '__init_subclass__',
 '__int__',
 '__invert__',
 '__le__',
 '__lshift__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__round__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__trunc__',
 '__xor__',
 'as_integer_ratio',
 'bit_length',
 'conjugate',
 'denominator',
 'from_bytes',
 'imag',
 'numerator',
 'real',
 'to_bytes']
[133]:
i + 3
[133]:
669
[134]:
i.__add__(3)
[134]:
669

Einschub: String-Vergleich vs. Integer-Vergleich

[135]:
s1 = 'abc'
s2 = 'def'
[136]:
s1 < s2
[136]:
True
[137]:
num1 = '123'
num2 = '4'
[138]:
ord('1')
[138]:
49
[139]:
ord('4')
[139]:
52
[140]:
num1 < num2
[140]:
True
[141]:
int(num1) < int(num2)
[141]:
False

Strings

[142]:
s = "Hallo"
[143]:
s += ', Joerg'
[144]:
s
[144]:
'Hallo, Joerg'
[145]:
s1 = 'Guten Morgen'
s2 = 'Joerg'
[146]:
gesamter_gruss = s1 + ', ' + s2
[147]:
gesamter_gruss
[147]:
'Guten Morgen, Joerg'
[148]:
s = 'HALLO'
s = s.lower()
s
[148]:
'hallo'

Random Numbers

[149]:
import random
[150]:
random.randrange(1,7)
[150]:
3

Sequential Datatypes

[151]:
s = 'abc'
[152]:
s[0]
[152]:
'a'
[153]:
try:
    s[3]
except Exception as e:
    print(type(e), e)
<class 'IndexError'> string index out of range
[154]:
s = '12345'
s.isalpha()
[154]:
False
[155]:
s.isdigit()
[155]:
True
[156]:
l = [1, 'eins', 1.0]
[157]:
l.append('one')
[158]:
l
[158]:
[1, 'eins', 1.0, 'one']
[159]:
type(l)
[159]:
list
[160]:
l[0]
[160]:
1
[161]:
try:
    l[3]
except Exception as e:
    print(type(e), e)
[162]:
sex = 'f'
sex in ('f', 'F')
[162]:
True
[163]:
t = (1, 'eins', 1.0)
[164]:
try:
    t.append('one')
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'tuple' object has no attribute 'append'
[165]:
l1 = [1,2,3]
l2 = [4, 5, 6]
[166]:
l = l1 + l2
l
[166]:
[1, 2, 3, 4, 5, 6]
[167]:
t1 = (1,2,3)
t2 = (4,5,6)
t = t1+t2
t
[167]:
(1, 2, 3, 4, 5, 6)
[168]:
s = 'Hello World'
[169]:
len(s)
[169]:
11
[170]:
s[0]
[170]:
'H'
[171]:
s[10]
[171]:
'd'
[172]:
try:
    s[len(s)]
except Exception as e:
    print(type(e), e)
<class 'IndexError'> string index out of range
[173]:
s[len(s)-1]
[173]:
'd'
[174]:
s[-1]
[174]:
'd'
[175]:
l = [4, 1, 'one', 1.0, [1,2,3], 7]
[176]:
1 in l
[176]:
True
[177]:
1100 in l
[177]:
False
[178]:
len(l)
[178]:
6
[179]:
if 1 in l:
    print('jo eh')
jo eh
[180]:
excelsheet = [
    [1, 'Hansi', 'Hinterseer'],
    [2, 'Andreas', 'Gabalier'],
    [3, 'Helene', 'Fischer']
]
[181]:
len(excelsheet)
[181]:
3
[182]:
excelsheet[0]
[182]:
[1, 'Hansi', 'Hinterseer']
[183]:
excelsheet[0][1]
[183]:
'Hansi'
[184]:
excelsheet[1][2]
[184]:
'Gabalier'
[185]:
for row in excelsheet:
    print(row[2])
Hinterseer
Gabalier
Fischer
[186]:
namen = ''
[187]:
for row in excelsheet:
    namen += row[2] + ','
print(namen)
Hinterseer,Gabalier,Fischer,
[188]:
l = [1, 2, 3, 4]
l * 4
[188]:
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
[189]:
s = 'mississippi'
's' in s
[189]:
True
[190]:
'ss' in s
[190]:
True
[191]:
s.count('ss')
[191]:
2
[192]:
s.find('ss')
[192]:
2
[193]:
pos = s.find('ss')
[194]:
pos
[194]:
2
[195]:
s.find('ss', pos+1)
[195]:
5
[196]:
s.count('s')
[196]:
4
[197]:
s = '            sssklndkfgv fosvh s sd      \n\t                '
s.strip()
[197]:
'sssklndkfgv fosvh s sd'
[198]:
s = 'HALLO'.center(100)
[199]:
len(s)
[199]:
100

Indexing and Slicing

[200]:
s = 'Hello World'
[201]:
s[4]
[201]:
'o'
[202]:
s[0:5]
[202]:
'Hello'
[203]:
s[:5]
[203]:
'Hello'
[204]:
s[6:11]
[204]:
'World'
[205]:
s[6:]
[205]:
'World'
[206]:
s[6:-1]
[206]:
'Worl'
[207]:
s[2:9:2]
[207]:
'loWr'
[208]:
s[:]
[208]:
'Hello World'
[209]:
s[::-1]
[209]:
'dlroW olleH'

Slice Assignment

[210]:
l = [1,2,3, 'a','b','c', 9,10,11]
[211]:
l[3:6] = [4, 5, 6, 7, 8]
[212]:
l
[212]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

for Loops

[213]:
l = ['Caro', 'Joerg', 'Johanna', 'Philipp']
for element in l:
    print(element)
Caro
Joerg
Johanna
Philipp
[214]:
for element in 'abc':
    print(element)
a
b
c

range()

[215]:
for element in range(3, 7):
    print(element)
3
4
5
6
[216]:
for element in [3,4,5,6]:
    print(element)
3
4
5
6
[217]:
i = 0
while i<4:
    print(i)
    i += 1
0
1
2
3
[218]:
for i in range(4):
    print(i)
0
1
2
3
[219]:
r = range(4)
[220]:
type(r)
[220]:
range
[221]:
it = iter(r)
[222]:
next(it)
[222]:
0
[223]:
next(it)
[223]:
1
[224]:
next(it)
[224]:
2
[225]:
next(it)
[225]:
3
[226]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
<class 'StopIteration'>
[227]:
number = 0
while number < 20:
    if number % 2 == 0:
        print(number)
    number += 1
0
2
4
6
8
10
12
14
16
18
[228]:
def even_numbers_fun(begin, end):
    nums = []
    number = begin
    while number < end:
        if number % 2 == 0:
            nums.append(number)
        number += 1
    return nums
[229]:
for number in even_numbers_fun(3, 8):
    print(number)
4
6
[230]:
def even_numbers_gen(begin, end):
    number = begin
    while number < end:
        if number % 2 == 0:
            print('yielding', number)
            yield number
            print('continuing after yielding', number)
        number += 1
[231]:
for number in even_numbers_gen(3, 8):
    print(number)
yielding 4
4
continuing after yielding 4
yielding 6
6
continuing after yielding 6
[232]:
evennums = even_numbers_gen(3, 8)
[233]:
type(evennums)
[233]:
generator
[234]:
it = iter(evennums)
[235]:
next(it)
yielding 4
[235]:
4
[236]:
next(it)
continuing after yielding 4
yielding 6
[236]:
6
[237]:
try:
    next(it)
except Exception as e:
    print(type(e), e)
continuing after yielding 6
<class 'StopIteration'>

Filterketten

[238]:
for element in range(10):
    print(element)
0
1
2
3
4
5
6
7
8
9
[239]:
def even_filter(iterable):
    for element in iterable:
        if element % 2 == 0:
            yield element
[240]:
for num in even_filter(range(3, 50)):
    print(num)
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48

Zen

[257]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Compound Datatypes

Compound Datatypes By Example: List, Tuple

[34]:
l = [1,2,3]
[35]:
type(l)
[35]:
list
[36]:
l
[36]:
[1, 2, 3]
[37]:
l.append(4)
l
[37]:
[1, 2, 3, 4]
[38]:
l.extend([5, 6, 7])
[39]:
l
[39]:
[1, 2, 3, 4, 5, 6, 7]
[40]:
l.append([8, 9])
l
[40]:
[1, 2, 3, 4, 5, 6, 7, [8, 9]]
[247]:
del l[3]
[248]:
l
[248]:
[1, 2, 3, 5, 6, 7, [8, 9]]
[249]:
l.append('hundert')
[250]:
l
[250]:
[1, 2, 3, 5, 6, 7, [8, 9], 'hundert']
[251]:
a = 'tausend'
l.append(a)
[252]:
l
[252]:
[1, 2, 3, 5, 6, 7, [8, 9], 'hundert', 'tausend']
[254]:
l.insert(3, 'aaa')
[255]:
l
[255]:
[1, 2, 3, 'aaa', 5, 6, 7, [8, 9], 'hundert', 'tausend']
[269]:
t1 = (1,2,3)
t2 = (4,5,6)
[270]:
t = t1 + t2
t
[270]:
(1, 2, 3, 4, 5, 6)
[272]:
try:
    t.append(7)
except Exception as e:
    print(type(e), e)
<class 'AttributeError'> 'tuple' object has no attribute 'append'
[273]:
sex = 'f'
if sex in ('f', 'F'):
    print('Mrs.')
Mrs.

List Comprehensions

[258]:
def squares(numbers):
    sqs = []
    for num in numbers:
        sqs.append(num**2)
    return sqs
[261]:
l = squares([2,3,1,5,8])
l
[261]:
[4, 9, 1, 25, 64]
[263]:
l = [num**2 for num in [2,3,1,5,8]]
l
[263]:
[4, 9, 1, 25, 64]
[266]:
l = [num**2 for num in [2,3,1,5,8] if num % 2 == 0]
l
[266]:
[4, 64]

Compound Datatypes By Example: Dictionary

[274]:
translation_table = {
    1: 'one',
    2: 'two',
    3: 'three'
}
[275]:
translation_table[1]
[275]:
'one'
[277]:
translation_table[4] = 'four'
[279]:
translation_table[4] = 'vier'
[280]:
del translation_table[1]
[281]:
translation_table
[281]:
{2: 'two', 3: 'three', 4: 'vier'}
[282]:
users = {
    '1037190666': ('Joerg', 'Faschingbauer'),
    '1234250497': ('Caro', 'Faschingbauer')
}
[283]:
users['1037190666']
[283]:
('Joerg', 'Faschingbauer')
[284]:
for element in users:
    print(element)
1037190666
1234250497
[286]:
for key in users.keys():
    print(key)
1037190666
1234250497
[287]:
for value in users.values():
    print(value)
('Joerg', 'Faschingbauer')
('Caro', 'Faschingbauer')
[288]:
for element in users.items():
    print(element)
('1037190666', ('Joerg', 'Faschingbauer'))
('1234250497', ('Caro', 'Faschingbauer'))

Datensatz als Dictionary?

[21]:
joerg = {
    'svnr': '1037190666',
    'firstname': 'Joerg',
    'lastname': 'Faschingbauer',
}
[22]:
caro = {
    'svnr': '1234250597',
    'firstname': 'Caro',
    'lastname': 'Faschingbauer',
}

Tuple Unpacking

[292]:
for element in users.items():
    svnr = element[0]
    value = element[1]
    firstname = value[0]
    lastname = value[1]

    print('svnr:', svnr, ', firstname:', firstname, ', lastname:', lastname)
svnr: 1037190666 , firstname: Joerg , lastname: Faschingbauer
svnr: 1234250497 , firstname: Caro , lastname: Faschingbauer
[295]:
for svnr, user in users.items():
    firstname = user[0]
    lastname = user[1]

    print('svnr:', svnr, ', firstname:', firstname, ', lastname:', lastname)
svnr: 1037190666 , firstname: Joerg , lastname: Faschingbauer
svnr: 1234250497 , firstname: Caro , lastname: Faschingbauer
[298]:
for svnr, user in users.items():
    firstname, lastname = user

    print('svnr:', svnr, ', firstname:', firstname, ', lastname:', lastname)
svnr: 1037190666 , firstname: Joerg , lastname: Faschingbauer
svnr: 1234250497 , firstname: Caro , lastname: Faschingbauer
[297]:
for svnr, (firstname, lastname) in users.items():
    print('svnr:', svnr, ', firstname:', firstname, ', lastname:', lastname)
svnr: 1037190666 , firstname: Joerg , lastname: Faschingbauer
svnr: 1234250497 , firstname: Caro , lastname: Faschingbauer

JSON (Javascript Object Notation)

[299]:
users
[299]:
{'1037190666': ('Joerg', 'Faschingbauer'),
 '1234250497': ('Caro', 'Faschingbauer')}
[300]:
import json
[301]:
users_json_string = json.dumps(users)
[302]:
users_json_string
[302]:
'{"1037190666": ["Joerg", "Faschingbauer"], "1234250497": ["Caro", "Faschingbauer"]}'

Jetzt liest der Kontrahent den String vom Kabel und verwandelt ihn zurueck in Python

[304]:
gelesenes_ding_wieder_als_dict = json.loads(users_json_string)
[306]:
gelesenes_ding_wieder_als_dict
[306]:
{'1037190666': ['Joerg', 'Faschingbauer'],
 '1234250497': ['Caro', 'Faschingbauer']}

Compound Datatypes By Example: Set

[7]:
s = { 1, 'eins', 1.0, 2, 3 }
len(s)
[7]:
4
[8]:
'eins' in s
[8]:
True
[9]:
1 in s
[9]:
True
[11]:
1.0 in s
[11]:
True
[12]:
s.add('zwei')
[14]:
'zwei' in s
[14]:
True
[16]:
s
[16]:
{1, 2, 3, 'eins', 'zwei'}
[23]:
1 == 1.0
[23]:
True
[18]:
s.add('zwei')
[19]:
s
[19]:
{1, 2, 3, 'eins', 'zwei'}
[24]:
s.remove('eins')
[25]:
'eins' in s
[25]:
False
[27]:
s
[27]:
{1, 2, 3, 'zwei'}
[28]:
s1 = {1,2,3,4}
s2 = {3,4,5,6}
[29]:
s1 | s2
[29]:
{1, 2, 3, 4, 5, 6}
[30]:
s1 & s2
[30]:
{3, 4}
[31]:
l = [4,7,1,3]
s = set(l)
[32]:
s
[32]:
{1, 3, 4, 7}
[33]:
s = set('abcd')
s
[33]:
{'a', 'b', 'c', 'd'}

Functions

[41]:
print('hallo schatz')
hallo schatz
[42]:
i = 1
[43]:
if i == 1:
    print('jo eh')
jo eh
[44]:
import sys
[45]:
sys.platform
[45]:
'linux'
[48]:
print('hallo', 'schatz', 1, i, sep=',')
hallo,schatz,1,1
[49]:
l = [1,2,3]
l.append(4)
[50]:
l
[50]:
[1, 2, 3, 4]
[51]:
a = 100
b = 200
[52]:
if a < b:
    print(b)
else:
    print(a)
200
[59]:
def maximum(a, b):
    print('local a:', a)
    print('local b:', b)
    if a < b:
        return b
    else:
        return a
[60]:
maximum(50, 60)
local a: 50
local b: 60
[60]:
60
[61]:
maximum(1, 2)
local a: 1
local b: 2
[61]:
2
[62]:
a = 300
b = 2000
[63]:
maximum(3,4)
local a: 3
local b: 4
[63]:
4
[64]:
a
[64]:
300
[65]:
b
[65]:
2000
[66]:
erich = 59
koxi = 53
[67]:
maximum(erich, koxi)
local a: 59
local b: 53
[67]:
59
[70]:
import random
maximum(random.randrange(40), 30)
local a: 35
local b: 30
[70]:
35
[71]:
print('hallo schatz')
hallo schatz
[72]:
wert = print('hallo schatz')
hallo schatz
[73]:
print(wert)
None
[74]:
def hatkeinenwert():
    pass
[75]:
wert = hatkeinenwert()
print(wert)
None

Das Letzte Beispiel am Letzten Tag

[81]:
joerg = {
    'firstname': 'Joerg',
    'lastname': 'Faschingbauer',
    'svnr': '1037190666',
}
[82]:
fn = joerg['firstname']
print(fn)
Joerg
[79]:
html = '''
<ul>
<li>Joerg</li>
<li>Faschingbauer</li>
<li>1037190666</li>
</ul>

'''
[86]:
fn = 'Joerg'
ln = 'Faschingbauer'
nr = '1037190666'
[89]:
html = '<ul>\n  <li>' + fn + '</li>\n  <li>' + ln + '</li>\n  <li>' + nr + '</li>\n</ul>'
print(html)
<ul>
  <li>Joerg</li>
  <li>Faschingbauer</li>
  <li>1037190666</li>
</ul>