Program Flow

if, else, elif

cond1, cond2 = True, False
if cond1:
    print("cond1 is True")

elif cond2:
    print("will never happen if dond1 is True")

else:
    print("cond1 and cond2 are False")
cond1 is True

Please note that program blocks are defined by their indentation level.

if cond1:
    if not cond2:
        print("cond1 is True and cond2 is False")

print("I'm always here!")
cond1 is True and cond2 is False
I'm always here!
if cond1 and not cond2:
    print("cond1 is True and cond2 is False")
cond1 is True and cond2 is False

Loops

for

for loops execute an program block for each element in a list:

for c in range(5):
    print(c+1)
1
2
3
4
5
for letter in 'Hallo':
    print('The letter is: {}'.format(letter))
The letter is: H
The letter is: a
The letter is: l
The letter is: l
The letter is: o
for magnetic_mineral in ('magnetite', 'hematite', 'greigite'):
    print( magnetic_mineral)
magnetite
hematite
greigite

enumerate give access to the indices when needed

for idx, c in enumerate(range(-3,3)):
    print(idx, c, idx*c)
0 -3 0
1 -2 -2
2 -1 -2
3 0 0
4 1 4
5 2 10
for x in 'ABCDE':
    for y in range(4):
        print( "{}{}".format(x,y))
A0
A1
A2
A3
B0
B1
B2
B3
C0
C1
C2
C3
D0
D1
D2
D3
E0
E1
E2
E3

List comprehensions

instead of doing something like this:

cubes = []
for c in range(4):
    cubes.append(c**3)
print(cubes)
[0, 1, 8, 27]

we can write:

[n**3 for n in range(4)]
[0, 1, 8, 27]
[(x,x**2) for x in range(1,5)]
[(1, 1), (2, 4), (3, 9), (4, 16)]
[s.upper() for s in ['small', 'little', 'tiny']]
['SMALL', 'LITTLE', 'TINY']
["{}{}".format(x,y) for x in "ABCDE" for y in range(4)]
['A0',
 'A1',
 'A2',
 'A3',
 'B0',
 'B1',
 'B2',
 'B3',
 'C0',
 'C1',
 'C2',
 'C3',
 'D0',
 'D1',
 'D2',
 'D3',
 'E0',
 'E1',
 'E2',
 'E3']
[x for x in range(10) if x > 3 and x < 8]
[4, 5, 6, 7]
vec = [[1,2,3], [4,5,6], [7,8,9]]
[num for elem in vec for num in elem if num % 2 == 0]
[2, 4, 6, 8]

Dictionary comprehensions

{x.upper(): x*3 for x in 'abcd'}
{'A': 'aaa', 'B': 'bbb', 'C': 'ccc', 'D': 'ddd'}

while

c = 0
while c < 5:
    c += 1
    print(c)
print("done")
1
2
3
4
5
done

Functions

def f():
    print("got called")
f()
got called
def sqrt(n):
    """
    return square root of n
    """
    return n**0.5
sqrt(2)
1.4142135623730951
def mul(a,b):
    """
    multiply a and b
    """
    return a*b

mul(2,3)
6
def div(a,b):
    """
    divide a by b
    return int division and reminder
    """
    return a // b, a % b

div(20,6)
(3, 2)

docstrings can be retrieved by builtin help function

help(div)
Help on function div in module __main__:

div(a, b)
    divide a by b
    return int division and reminder

works with any object that has a doc string

help(sorted)
Help on built-in function sorted in module builtins:

sorted(...)
    sorted(iterable, key=None, reverse=False) --> new sorted list
def add(a,b=1):
    """
    add a and b
    if b is not given it is assumed to be 1
    """
    return a+b

print(add(2,3))
print(add(7))
5
8

anonymous functions: lambda

square = lambda n: n**2
square(3)
9

for efficient computation, functions can be applied to a list of parameters

map( square, range(10))
<map at 0x7f1394041c18>
map( lambda x: x**3, range(10))
<map at 0x7f1394041e10>

Exceptions

exceptions output error messages

1+a
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-33-f9dd4f57d0fd> in <module>()
----> 1 1+a


NameError: name 'a' is not defined
a = 2
a[1]
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-34-79d66ab95ee2> in <module>()
      1 a = 2
----> 2 a[1]


TypeError: 'int' object is not subscriptable
try:
    zz *= 2
except NameError:
    print( "Caught NameError: zz not known")
Caught NameError: zz not known

Modules and Namespaces

import math
math.cos( math.radians(45))
0.7071067811865476
from math import sin, degrees
sin( degrees(45))
0.8060754911159176
dir(math)
['__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'acos',
 'acosh',
 'asin',
 'asinh',
 'atan',
 'atan2',
 'atanh',
 'ceil',
 'copysign',
 'cos',
 'cosh',
 'degrees',
 'e',
 'erf',
 'erfc',
 'exp',
 'expm1',
 'fabs',
 'factorial',
 'floor',
 'fmod',
 'frexp',
 'fsum',
 'gamma',
 'hypot',
 'isfinite',
 'isinf',
 'isnan',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'log2',
 'modf',
 'pi',
 'pow',
 'radians',
 'sin',
 'sinh',
 'sqrt',
 'tan',
 'tanh',
 'trunc']
help(math)
Help on module math:

NAME
    math

MODULE REFERENCE
    http://docs.python.org/3.4/library/math

    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 is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(...)
        acos(x)

        Return the arc cosine (measured in radians) of x.

    acosh(...)
        acosh(x)

        Return the inverse hyperbolic cosine of x.

    asin(...)
        asin(x)

        Return the arc sine (measured in radians) of x.

    asinh(...)
        asinh(x)

        Return the inverse hyperbolic sine of x.

    atan(...)
        atan(x)

        Return the arc tangent (measured in radians) of x.

    atan2(...)
        atan2(y, x)

        Return the arc tangent (measured in radians) of y/x.
        Unlike atan(y/x), the signs of both x and y are considered.

    atanh(...)
        atanh(x)

        Return the inverse hyperbolic tangent of x.

    ceil(...)
        ceil(x)

        Return the ceiling of x as an int.
        This is the smallest integral value >= x.

    copysign(...)
        copysign(x, y)

        Return a float with the magnitude (absolute value) of x but the sign
        of y. On platforms that support signed zeros, copysign(1.0, -0.0)
        returns -1.0.

    cos(...)
        cos(x)

        Return the cosine of x (measured in radians).

    cosh(...)
        cosh(x)

        Return the hyperbolic cosine of x.

    degrees(...)
        degrees(x)

        Convert angle x from radians to degrees.

    erf(...)
        erf(x)

        Error function at x.

    erfc(...)
        erfc(x)

        Complementary error function at x.

    exp(...)
        exp(x)

        Return e raised to the power of x.

    expm1(...)
        expm1(x)

        Return exp(x)-1.
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.

    fabs(...)
        fabs(x)

        Return the absolute value of the float x.

    factorial(...)
        factorial(x) -> Integral

        Find x!. Raise a ValueError if x is negative or non-integral.

    floor(...)
        floor(x)

        Return the floor of x as an int.
        This is the largest integral value <= x.

    fmod(...)
        fmod(x, y)

        Return fmod(x, y), according to platform C.  x % y may differ.

    frexp(...)
        frexp(x)

        Return the mantissa and exponent of x, as pair (m, e).
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.

    fsum(...)
        fsum(iterable)

        Return an accurate floating point sum of values in the iterable.
        Assumes IEEE-754 floating point arithmetic.

    gamma(...)
        gamma(x)

        Gamma function at x.

    hypot(...)
        hypot(x, y)

        Return the Euclidean distance, sqrt(x*x + y*y).

    isfinite(...)
        isfinite(x) -> bool

        Return True if x is neither an infinity nor a NaN, and False otherwise.

    isinf(...)
        isinf(x) -> bool

        Return True if x is a positive or negative infinity, and False otherwise.

    isnan(...)
        isnan(x) -> bool

        Return True if x is a NaN (not a number), and False otherwise.

    ldexp(...)
        ldexp(x, i)

        Return x * (2**i).

    lgamma(...)
        lgamma(x)

        Natural logarithm of absolute value of Gamma function at x.

    log(...)
        log(x[, base])

        Return the logarithm of x to the given base.
        If the base not specified, returns the natural logarithm (base e) of x.

    log10(...)
        log10(x)

        Return the base 10 logarithm of x.

    log1p(...)
        log1p(x)

        Return the natural logarithm of 1+x (base e).
        The result is computed in a way which is accurate for x near zero.

    log2(...)
        log2(x)

        Return the base 2 logarithm of x.

    modf(...)
        modf(x)

        Return the fractional and integer parts of x.  Both results carry the sign
        of x and are floats.

    pow(...)
        pow(x, y)

        Return x**y (x to the power of y).

    radians(...)
        radians(x)

        Convert angle x from degrees to radians.

    sin(...)
        sin(x)

        Return the sine of x (measured in radians).

    sinh(...)
        sinh(x)

        Return the hyperbolic sine of x.

    sqrt(...)
        sqrt(x)

        Return the square root of x.

    tan(...)
        tan(x)

        Return the tangent of x (measured in radians).

    tanh(...)
        tanh(x)

        Return the hyperbolic tangent of x.

    trunc(...)
        trunc(x:Real) -> Integral

        Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    pi = 3.141592653589793

FILE
    /home/wack/bin/anaconda3/lib/python3.4/lib-dynload/math.cpython-34m.so
help(math.sqrt)
Help on built-in function sqrt in module math:

sqrt(...)
    sqrt(x)

    Return the square root of x.