Program Flow ============ if, else, elif -------------- .. code:: python cond1, cond2 = True, False .. code:: python if cond1: print("cond1 is True") elif cond2: print("will never happen if dond1 is True") else: print("cond1 and cond2 are False") .. parsed-literal:: cond1 is True Please note that program blocks are defined by their indentation level. .. code:: python if cond1: if not cond2: print("cond1 is True and cond2 is False") print("I'm always here!") .. parsed-literal:: cond1 is True and cond2 is False I'm always here! .. code:: python if cond1 and not cond2: print("cond1 is True and cond2 is False") .. parsed-literal:: cond1 is True and cond2 is False Loops ----- for ~~~ for loops execute an program block for each element in a list: .. code:: python for c in range(5): print(c+1) .. parsed-literal:: 1 2 3 4 5 .. code:: python for letter in 'Hallo': print('The letter is: {}'.format(letter)) .. parsed-literal:: The letter is: H The letter is: a The letter is: l The letter is: l The letter is: o .. code:: python for magnetic_mineral in ('magnetite', 'hematite', 'greigite'): print( magnetic_mineral) .. parsed-literal:: magnetite hematite greigite enumerate give access to the indices when needed .. code:: python for idx, c in enumerate(range(-3,3)): print(idx, c, idx*c) .. parsed-literal:: 0 -3 0 1 -2 -2 2 -1 -2 3 0 0 4 1 4 5 2 10 .. code:: python for x in 'ABCDE': for y in range(4): print( "{}{}".format(x,y)) .. parsed-literal:: 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: .. code:: python cubes = [] for c in range(4): cubes.append(c**3) print(cubes) .. parsed-literal:: [0, 1, 8, 27] we can write: .. code:: python [n**3 for n in range(4)] .. parsed-literal:: [0, 1, 8, 27] .. code:: python [(x,x**2) for x in range(1,5)] .. parsed-literal:: [(1, 1), (2, 4), (3, 9), (4, 16)] .. code:: python [s.upper() for s in ['small', 'little', 'tiny']] .. parsed-literal:: ['SMALL', 'LITTLE', 'TINY'] .. code:: python ["{}{}".format(x,y) for x in "ABCDE" for y in range(4)] .. parsed-literal:: ['A0', 'A1', 'A2', 'A3', 'B0', 'B1', 'B2', 'B3', 'C0', 'C1', 'C2', 'C3', 'D0', 'D1', 'D2', 'D3', 'E0', 'E1', 'E2', 'E3'] .. code:: python [x for x in range(10) if x > 3 and x < 8] .. parsed-literal:: [4, 5, 6, 7] .. code:: python vec = [[1,2,3], [4,5,6], [7,8,9]] [num for elem in vec for num in elem if num % 2 == 0] .. parsed-literal:: [2, 4, 6, 8] Dictionary comprehensions ^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python {x.upper(): x*3 for x in 'abcd'} .. parsed-literal:: {'A': 'aaa', 'B': 'bbb', 'C': 'ccc', 'D': 'ddd'} while ~~~~~ .. code:: python c = 0 while c < 5: c += 1 print(c) print("done") .. parsed-literal:: 1 2 3 4 5 done Functions --------- .. code:: python def f(): print("got called") .. code:: python f() .. parsed-literal:: got called .. code:: python def sqrt(n): """ return square root of n """ return n**0.5 .. code:: python sqrt(2) .. parsed-literal:: 1.4142135623730951 .. code:: python def mul(a,b): """ multiply a and b """ return a*b mul(2,3) .. parsed-literal:: 6 .. code:: python def div(a,b): """ divide a by b return int division and reminder """ return a // b, a % b div(20,6) .. parsed-literal:: (3, 2) docstrings can be retrieved by builtin help function .. code:: python help(div) .. parsed-literal:: 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 .. code:: python help(sorted) .. parsed-literal:: Help on built-in function sorted in module builtins: sorted(...) sorted(iterable, key=None, reverse=False) --> new sorted list .. code:: python 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)) .. parsed-literal:: 5 8 anonymous functions: lambda .. code:: python square = lambda n: n**2 .. code:: python square(3) .. parsed-literal:: 9 for efficient computation, functions can be applied to a list of parameters .. code:: python map( square, range(10)) .. parsed-literal:: .. code:: python map( lambda x: x**3, range(10)) .. parsed-literal:: Exceptions ---------- exceptions output error messages .. code:: python 1+a :: --------------------------------------------------------------------------- NameError Traceback (most recent call last) in () ----> 1 1+a NameError: name 'a' is not defined .. code:: python a = 2 a[1] :: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () 1 a = 2 ----> 2 a[1] TypeError: 'int' object is not subscriptable .. code:: python try: zz *= 2 except NameError: print( "Caught NameError: zz not known") .. parsed-literal:: Caught NameError: zz not known Modules and Namespaces ---------------------- .. code:: python import math .. code:: python math.cos( math.radians(45)) .. parsed-literal:: 0.7071067811865476 .. code:: python from math import sin, degrees .. code:: python sin( degrees(45)) .. parsed-literal:: 0.8060754911159176 .. code:: python dir(math) .. parsed-literal:: ['__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'] .. code:: python help(math) .. parsed-literal:: 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 .. code:: python help(math.sqrt) .. parsed-literal:: Help on built-in function sqrt in module math: sqrt(...) sqrt(x) Return the square root of x.