What's in Python belly?

Ipython special features

In [1]:
import IPython
IPython.__version__
Out[1]:
'5.3.0'

A magic command is a command beginning with %. In most cases it also works without %.

In [7]:
%pwd
Out[7]:
'/Users/alba/Documents/technique/python'

Run shell commands:

In [8]:
!stat .
16777218 15892769 drwx------ 39 alba staff 0 1326 "Jul 14 19:07:17 2017" "Jul 14 19:06:08 2017" "Jul 14 19:06:08 2017" "Jan  1 01:00:00 1970" 4096 0 0 .
In [16]:
help('help')
Help on _Helper in module _sitebuiltins object:

help = class _Helper(builtins.object)
 |  Define the builtin 'help'.
 |  
 |  This is a wrapper around pydoc.help that provides a helpful message
 |  when 'help' is typed at the Python interactive prompt.
 |  
 |  Calling help() at the Python prompt starts an interactive help session.
 |  Calling help(thing) prints help for the python object 'thing'.
 |  
 |  Methods defined here:
 |  
 |  __call__(self, *args, **kwds)
 |      Call self as a function.
 |  
 |  __repr__(self)
 |      Return repr(self).
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

Succesive evaluations:

In [15]:
print(1/2**2)
print(1/3**2)
print(1/4**2)
1/5**2
0.25
0.1111111111111111
0.0625
Out[15]:
0.04

Final semicolumn suppresses output:

In [20]:
1;1/2**2;1/3**2;1/4**2;

Avoid using print:

In [1]:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

Output (limited) history:

In [21]:
1/2**2
1/3**2
1/4**2
1/5**2
Out[21]:
0.25
Out[21]:
0.1111111111111111
Out[21]:
0.0625
Out[21]:
0.04
In [22]:
_
Out[22]:
0.04
In [23]:
1
1/2**2
1/3**2
1/4**2
Out[23]:
1
Out[23]:
0.25
Out[23]:
0.1111111111111111
Out[23]:
0.0625
In [24]:
_+__+___
Out[24]:
0.4236111111111111
In [25]:
1
1/2**2
1/3**2
1/4**2
Out[25]:
1
Out[25]:
0.25
Out[25]:
0.1111111111111111
Out[25]:
0.0625
In [26]:
_+__+___+____ # fails
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-26-4a2c57620ff6> in <module>()
----> 1 _+__+___+____ # fails

NameError: name '____' is not defined

Input history:

In [27]:
recall 26 # In number
In [ ]:
_+__+___+____ # fails

Calculating

Variables

In [28]:
x=17
y=5
q,r=divmod(x,y)
x==y*q+r

del x,y,q,r
Out[28]:
True

Builtin numeric classes

In [29]:
x=(3+4*6)**2
x
Out[29]:
729

Class and type are more or less synonymous. "By default, classes are constructed using type(). "

In [30]:
type(x)
x.__class__
Out[30]:
int
Out[30]:
int

Euclidean division

In [31]:
divmod(17,5)
Out[31]:
(3, 2)

This should be undefined:

In [32]:
0**0   # Not equal to 1!
Out[32]:
1
In [33]:
16**1/2
16**(1/2)
Out[33]:
8.0
Out[33]:
4.0
In [34]:
(3+4*5)**2.
type(_)
Out[34]:
529.0
Out[34]:
float
In [35]:
int(-1.000000000000000000000000000001)
Out[35]:
-1

Infinity

In [36]:
1+float("inf")
Out[36]:
inf
In [37]:
1245312314342342342342342342342342342342342344243<float("inf")
Out[37]:
True

Complex numbers

In [38]:
(1+2j)**2
(1j)**2
Out[38]:
(-3+4j)
Out[38]:
(-1+0j)
In [39]:
complex(1,2)-(1+2j)
Out[39]:
0j
In [40]:
complex(1,2)**2
Out[40]:
(-3+4j)
In [41]:
1j**2
j**2 # fails
Out[41]:
(-1+0j)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-41-bd4c87b20cf8> in <module>()
      1 1j**2
----> 2 j**2

NameError: name 'j' is not defined

Builtin non numeric classes

Boolean

In [42]:
True & False
True & True
False | True
False | False
Out[42]:
False
Out[42]:
True
Out[42]:
True
Out[42]:
False
In [43]:
float(0)==0
type(_)
int(True)
bool(0)
Out[43]:
True
Out[43]:
bool
Out[43]:
1
Out[43]:
False

Tuple

Parenthesis can be used not only for grouping but also for tuples.

In [44]:
(1,1,1,1)
Out[44]:
(1, 1, 1, 1)
In [45]:
type(_)
Out[45]:
tuple
In [46]:
type(())
Out[46]:
tuple
In [47]:
(0,)*5
Out[47]:
(0, 0, 0, 0, 0)
In [48]:
(1,2,3,4)[-2]

((3,1,2),(2,0))[1][-1]

(1,2,3,4)[1:3]
Out[48]:
3
Out[48]:
0
Out[48]:
(2, 3)
In [49]:
(1,2,3)*2
(1,2,3)+(1,2,3)
(1,2,3)+1 # fails
Out[49]:
(1, 2, 3, 1, 2, 3)
Out[49]:
(1, 2, 3, 1, 2, 3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-49-04793aa7aaf7> in <module>()
      1 (1,2,3)*2
      2 (1,2,3)+(1,2,3)
----> 3 (1,2,3)+1

TypeError: can only concatenate tuple (not "int") to tuple

Tuples are iterable, reusable, immutable.

In [50]:
tuple1=(1,2,3)
print(tuple1)

x,y,z=tuple1

x,y,z=tuple1

tuple1[1]=4  # fails
(1, 2, 3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-389797329205> in <module>()
      6 x,y,z=tuple1
      7 
----> 8 tuple1[1]=4  # fails

TypeError: 'tuple' object does not support item assignment
In [51]:
del tuple1,x,y,z
In [ ]:
 

range is a subclass of equally spaced integer tuple.

In [53]:
range1=range(0,8,2)

range1 # Does not evaluate as tuple.

type(range1)  # not tuple

x,y,z,t=range1

x,y,z,t=range1

range1[3]=4 # fails
Out[53]:
range(0, 8, 2)
Out[53]:
range
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-53-8e414441ac3a> in <module>()
      9 x,y,z,t=range1
     10 
---> 11 range1[3]=4 # fails

TypeError: 'range' object does not support item assignment
In [54]:
del range1,x,y,z,t

String

In [55]:
"a"*10
Out[55]:
'aaaaaaaaaa'
In [56]:
type(_)
Out[56]:
str
In [57]:
int('123')
Out[57]:
123
In [58]:
str(123)
Out[58]:
'123'
In [59]:
"je "+"suis"
Out[59]:
'je suis'
In [60]:
_[:2]
Out[60]:
'je'
In [61]:
x,y,z="abc"
print(x,y,z)

print(x,y,z)

"abc"[1]='x' # fails
a b c
a b c
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-61-c2ef369339ba> in <module>()
      4 print(x,y,z)
      5 
----> 6 "abc"[1]='x'

TypeError: 'str' object does not support item assignment
In [62]:
del x,y,z
In [41]:
"""
multiple line
embedded Python comment
""";

List

Square brackets can be used not only for positional arguments but also lists.

In [63]:
[0]*5
Out[63]:
[0, 0, 0, 0, 0]
In [64]:
type([])
Out[64]:
list
In [65]:
[1,2,3,4][1:3]
Out[65]:
[2, 3]
In [67]:
[['a', 'b', 'c'], [1, 2, 3]][0][-1]

[['a', 'b', 'c'], [1, 2, 3]][0,-1] # fails
Out[67]:
'c'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-67-7f71eee07ad3> in <module>()
      1 [['a', 'b', 'c'], [1, 2, 3]][0][-1]
      2 
----> 3 [['a', 'b', 'c'], [1, 2, 3]][0,-1] # fails

TypeError: list indices must be integers or slices, not tuple
In [68]:
[1,2]+[3,4]
Out[68]:
[1, 2, 3, 4]

Lists are iterable and reusable.

In [69]:
list1=[2,1,0]
x,y,z=list1
print(x,y,z)

x,y,z=list1
print(x,y,z)
del list1,x,y,z
2 1 0
2 1 0

Lists are mutable.

In [70]:
list1=[1,2,3]

list1

list1[1]=100
list1

del list1
Out[70]:
[1, 2, 3]
Out[70]:
[1, 100, 3]

Set

In [71]:
{1,3,1,2}
Out[71]:
{1, 2, 3}
In [72]:
{1,3,1,2}-{1,1}
Out[72]:
{2, 3}
In [92]:
{1,3,1}+{3,4} # fails
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-92-66b2b86287e4> in <module>()
----> 1 {1,3,1}+{3,4}

TypeError: unsupported operand type(s) for +: 'set' and 'set'
In [73]:
set("parisien")==set("aspirine")
Out[73]:
True
In [74]:
for i in {1,3,1,2}:
    i
Out[74]:
1
Out[74]:
2
Out[74]:
3
In [75]:
set1={1,3,1,2}
x,y,z=set1
print(x,y,z)

x,y,z=set1
print(x,y,z)

del set1,x,y,z
1 2 3
1 2 3

Dictionary

In [76]:
birthdates={'Robert':'19301223','Géal':'19321111'}
In [77]:
type(birthdates)
Out[77]:
dict
In [78]:
birthdates['Robert']='19171010'
birthdates
Out[78]:
{'Géal': '19321111', 'Robert': '19171010'}
In [79]:
for i in birthdates:
    print(i,birthdates[i])
Robert 19171010
Géal 19321111

Generator

In [80]:
(x*x for x in range(40))
type(_)
Out[80]:
<generator object <genexpr> at 0x1150de0f8>
Out[80]:
generator

Generators are iterable but not reusable (hence not mutable).

In [81]:
generator1=(i for i in range(3))

for i in generator1:
    print(i)
    
for i in generator1:
    print(i)  # Prints nothing.

del generator1
0
1
2

Attributes

Almost everything in python is object and has attributes.

In [82]:
dir(1+1j)
Out[82]:
['__abs__',
 '__add__',
 '__bool__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__int__',
 '__le__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rmod__',
 '__rmul__',
 '__rpow__',
 '__rsub__',
 '__rtruediv__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 'conjugate',
 'imag',
 'real']
In [83]:
(1+1j).conjugate()
(1+1j).real
Out[83]:
(1-1j)
Out[83]:
1.0
In [84]:
dir("abc")
Out[84]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']
In [85]:
help(str.partition)
Help on method_descriptor:

partition(...)
    S.partition(sep) -> (head, sep, tail)
    
    Search for the separator sep in S, and return the part before it,
    the separator itself, and the part after it.  If the separator is not
    found, return S and two empty strings.

In [86]:
"maître corbeau, par l'odeur alléché".partition(",") 
 
"maître corbeau, par l'odeur alléché".split("o") 

"abc".upper()
Out[86]:
('maître corbeau', ',', " par l'odeur alléché")
Out[86]:
['maître c', "rbeau, par l'", 'deur alléché']
Out[86]:
'ABC'
In [87]:
type(b'201405064324234233FDA3')
Out[87]:
bytes
In [88]:
b'201405064324234233FDA3'.decode('ascii')
Out[88]:
'201405064324234233FDA3'
In [89]:
type(_)
Out[89]:
str
In [90]:
x=[]
x.append(3)
x
del x
Out[90]:
[3]
In [91]:
{1,2}.union({2,3})
Out[91]:
{1, 2, 3}

Python files

Importing modules

In [93]:
import random
In [94]:
dir(random)
Out[94]:
['BPF',
 'LOG4',
 'NV_MAGICCONST',
 'RECIP_BPF',
 'Random',
 'SG_MAGICCONST',
 'SystemRandom',
 'TWOPI',
 '_BuiltinMethodType',
 '_MethodType',
 '_Sequence',
 '_Set',
 '__all__',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_acos',
 '_bisect',
 '_ceil',
 '_cos',
 '_e',
 '_exp',
 '_inst',
 '_itertools',
 '_log',
 '_pi',
 '_random',
 '_sha512',
 '_sin',
 '_sqrt',
 '_test',
 '_test_generator',
 '_urandom',
 '_warn',
 'betavariate',
 'choice',
 'choices',
 'expovariate',
 'gammavariate',
 'gauss',
 'getrandbits',
 'getstate',
 'lognormvariate',
 'normalvariate',
 'paretovariate',
 'randint',
 'random',
 'randrange',
 'sample',
 'seed',
 'setstate',
 'shuffle',
 'triangular',
 'uniform',
 'vonmisesvariate',
 'weibullvariate']
In [96]:
help(random.randrange)
Help on method randrange in module random:

randrange(start, stop=None, step=1, _int=<class 'int'>) method of random.Random instance
    Choose a random item from range(start, stop[, step]).
    
    This fixes the problem with randint() which includes the
    endpoint; in Python this is usually not what you want.

In [98]:
random.randrange(100)
Out[98]:
1
In [99]:
import math
In [102]:
dir(math)
Out[102]:
['__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',
 'gcd',
 'hypot',
 'inf',
 'isclose',
 'isfinite',
 'isinf',
 'isnan',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'log2',
 'modf',
 'nan',
 'pi',
 'pow',
 'radians',
 'sin',
 'sinh',
 'sqrt',
 'tan',
 'tanh',
 'tau',
 'trunc']
In [101]:
help(math.nan)
Help on float object:

class float(object)
 |  float(x) -> floating point number
 |  
 |  Convert a string or number to a floating point number, if possible.
 |  
 |  Methods defined here:
 |  
 |  __abs__(self, /)
 |      abs(self)
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __bool__(self, /)
 |      self != 0
 |  
 |  __divmod__(self, value, /)
 |      Return divmod(self, value).
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __float__(self, /)
 |      float(self)
 |  
 |  __floordiv__(self, value, /)
 |      Return self//value.
 |  
 |  __format__(...)
 |      float.__format__(format_spec) -> string
 |      
 |      Formats the float according to format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getformat__(...) from builtins.type
 |      float.__getformat__(typestr) -> string
 |      
 |      You probably don't want to use this function.  It exists mainly to be
 |      used in Python's test suite.
 |      
 |      typestr must be 'double' or 'float'.  This function returns whichever of
 |      'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the
 |      format of floating point numbers used by the C type named by typestr.
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __int__(self, /)
 |      int(self)
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __neg__(self, /)
 |      -self
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __pos__(self, /)
 |      +self
 |  
 |  __pow__(self, value, mod=None, /)
 |      Return pow(self, value, mod).
 |  
 |  __radd__(self, value, /)
 |      Return value+self.
 |  
 |  __rdivmod__(self, value, /)
 |      Return divmod(value, self).
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rfloordiv__(self, value, /)
 |      Return value//self.
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __round__(...)
 |      Return the Integral closest to x, rounding half toward even.
 |      When an argument is passed, work like built-in round(x, ndigits).
 |  
 |  __rpow__(self, value, mod=None, /)
 |      Return pow(value, self, mod).
 |  
 |  __rsub__(self, value, /)
 |      Return value-self.
 |  
 |  __rtruediv__(self, value, /)
 |      Return value/self.
 |  
 |  __setformat__(...) from builtins.type
 |      float.__setformat__(typestr, fmt) -> None
 |      
 |      You probably don't want to use this function.  It exists mainly to be
 |      used in Python's test suite.
 |      
 |      typestr must be 'double' or 'float'.  fmt must be one of 'unknown',
 |      'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
 |      one of the latter two if it appears to match the underlying C reality.
 |      
 |      Override the automatic determination of C-level floating point type.
 |      This affects how floats are converted to and from binary strings.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  __sub__(self, value, /)
 |      Return self-value.
 |  
 |  __truediv__(self, value, /)
 |      Return self/value.
 |  
 |  __trunc__(...)
 |      Return the Integral closest to x between 0 and x.
 |  
 |  as_integer_ratio(...)
 |      float.as_integer_ratio() -> (int, int)
 |      
 |      Return a pair of integers, whose ratio is exactly equal to the original
 |      float and with a positive denominator.
 |      Raise OverflowError on infinities and a ValueError on NaNs.
 |      
 |      >>> (10.0).as_integer_ratio()
 |      (10, 1)
 |      >>> (0.0).as_integer_ratio()
 |      (0, 1)
 |      >>> (-.25).as_integer_ratio()
 |      (-1, 4)
 |  
 |  conjugate(...)
 |      Return self, the complex conjugate of any float.
 |  
 |  fromhex(...) from builtins.type
 |      float.fromhex(string) -> float
 |      
 |      Create a floating-point number from a hexadecimal string.
 |      >>> float.fromhex('0x1.ffffp10')
 |      2047.984375
 |      >>> float.fromhex('-0x1p-1074')
 |      -5e-324
 |  
 |  hex(...)
 |      float.hex() -> string
 |      
 |      Return a hexadecimal representation of a floating-point number.
 |      >>> (-0.1).hex()
 |      '-0x1.999999999999ap-4'
 |      >>> 3.14159.hex()
 |      '0x1.921f9f01b866ep+1'
 |  
 |  is_integer(...)
 |      Return True if the float is an integer.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  imag
 |      the imaginary part of a complex number
 |  
 |  real
 |      the real part of a complex number

In [103]:
type(math.nan)
Out[103]:
float
In [106]:
1+math.nan
Out[106]:
nan
In [107]:
1+math.nan==math.nan
1+math.nan==1+math.nan
Out[107]:
False
Out[107]:
False
In [108]:
math.pi

math.cos(math.pi)

math.ceil(-2.3434)
Out[108]:
3.141592653589793
Out[108]:
-1.0
Out[108]:
-2

Is π a constant?

In [122]:
math.pi=22/7 # does not fail
math.pi # no change
Out[122]:
3.142857142857143
In [125]:
del math.pi

A module can be imported only once

In [126]:
import math
math.pi # fails
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-126-c96b093744e7> in <module>()
      1 import math
----> 2 math.pi

AttributeError: module 'math' has no attribute 'pi'

and relaod does not help.

In [127]:
import importlib
importlib.reload(math)
math.pi # fails
Out[127]:
<module 'math' from '/Users/alba/anaconda3/lib/python3.6/lib-dynload/math.cpython-36m-darwin.so'>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-127-85a617ac6426> in <module>()
      1 import importlib
      2 importlib.reload(math)
----> 3 math.pi

AttributeError: module 'math' has no attribute 'pi'
In [128]:
!pip install reimport
import reimport
help(reimport.reimport)
Requirement already satisfied: reimport in /Users/alba/anaconda3/lib/python3.6/site-packages
Help on function reimport in module reimport:

reimport(*modules)
    Reimport python modules. Multiple modules can be passed either by
    name or by reference. Only pure python modules can be reimported.
    
    For advanced control, global variables can be placed in modules
    that allows finer control of the reimport process.
    
    If a package module has a true value for "__package_reimport__"
    then that entire package will be reimported when any of its children
    packages or modules are reimported.
    
    If a package module defines __reimported__ it must be a callable
    function that accepts one argument and returns a bool. The argument
    is the reference to the old version of that module before any
    cleanup has happened. The function should normally return True to
    allow the standard reimport cleanup. If the function returns false
    then cleanup will be disabled for only that module. Any exceptions
    raised during the callback will be handled by traceback.print_exc,
    similar to what happens with tracebacks in the __del__ method.

In [130]:
reimport.reimport(math)
math.pi # fails
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-130-a05aa813b94c> in <module>()
----> 1 reimport.reimport(math)
      2 math.pi # fails

/Users/alba/anaconda3/lib/python3.6/site-packages/reimport.py in reimport(*modules)
     98     # Get names of all modules being reloaded
     99     for module in modules:
--> 100         name, target = _find_exact_target(module)
    101         if not target:
    102             raise ValueError("Module %r not found" % module)

/Users/alba/anaconda3/lib/python3.6/site-packages/reimport.py in _find_exact_target(module)
    315         name = module
    316     else:
--> 317         for name, mod in sys.modules.iteritems():
    318             if mod is module:
    319                 actualModule = module

AttributeError: 'dict' object has no attribute 'iteritems'

This seems to reload the math module as π is restored.

In [131]:
import sys
del sys.modules['math']
import math
math.pi
Out[131]:
3.141592653589793

Finally, restarting the kernel and importing is simpler and safer than reimporting.

Typing math. can be avoided by importing in global namespace.

In [132]:
from math import *
pi
cos(pi/2)
Out[132]:
3.141592653589793
Out[132]:
6.123233995736766e-17
In [133]:
import sys
sys.path
Out[133]:
['',
 '/Users/alba/Library/python',
 '/Users/alba/Documents/technique/python',
 '/Users/alba/anaconda3/lib/python36.zip',
 '/Users/alba/anaconda3/lib/python3.6',
 '/Users/alba/anaconda3/lib/python3.6/lib-dynload',
 '/Users/alba/anaconda3/lib/python3.6/site-packages',
 '/Users/alba/anaconda3/lib/python3.6/site-packages/Sphinx-1.5.6-py3.6.egg',
 '/Users/alba/anaconda3/lib/python3.6/site-packages/aeosa',
 '/Users/alba/anaconda3/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg',
 '/Users/alba/anaconda3/lib/python3.6/site-packages/IPython/extensions',
 '/Users/alba/.ipython']

Creating scripts or modules

For record or further use, calculations can be saved into script files or scripts. The script first line of may declare the program that is supposed to run the script, be it a python version or a shell (on unix systems). Interactive versions of python allow saving an interactive session into a script.

In [11]:
a=1
b=-(2+9)
c=2*9
In [12]:
print([(-b+i*(b**2-4*a*c)**(1/2))/(2*a) for i in [-1,1]])
[2.0, 9.0]
In [13]:
%save roots.py 12 # change number to above 
File `roots.py` exists. Overwrite (y/[N])?  y
The following commands were written to file `roots.py`:
print([(-b+i*(b**2-4*a*c)**(1/2))/(2*a) for i in [-1,1]])

Various ways of running files

In [14]:
%run roots.py # fails
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/Users/alba/Documents/technique/python/roots.py in <module>()
      1 # coding: utf-8
----> 2 print([(-b+i*(b**2-4*a*c)**(1/2))/(2*a) for i in [-1,1]])

/Users/alba/Documents/technique/python/roots.py in <listcomp>(.0)
      1 # coding: utf-8
----> 2 print([(-b+i*(b**2-4*a*c)**(1/2))/(2*a) for i in [-1,1]])

NameError: name 'b' is not defined

Run as if typed inline:

In [15]:
%run -i roots.py
[2.0, 9.0]
In [16]:
exec(open("roots.py").read(), globals())
[2.0, 9.0]
In [17]:
!cat executable.py
#!/usr/bin/env python3.5

print("bonjour")
In [18]:
!executable.py
bonjour

The difference between module and script is in the way the file is used, which affects the internal variable __name__, the value of which is __main__ for a script or the module name for a module.

In [19]:
!cat argv.py
print("__________________________________")
!python argv.py hello
# usage: % python argv.py bonjour 
if __name__ == "__main__":
    import sys
    print(sys.argv[1])
    print("This was a script.")

__________________________________
hello
This was a script.
In [23]:
!cat Fibonacci.py
#!/usr/bin/env python3.5
def fib(n):
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a + b
    print('\n') 


def fib1(n):    # write Fibonacci series up to n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

if __name__ == "__main__":
    print("used as script")
    print(global1)
    
else:
    print("used as module named ",__name__)


In [6]:
# restart kernel
import Fibonacci
used as module named  Fibonacci
In [7]:
Fibonacci.fib(10)
1 1 2 3 5 8 

Structured programming (branching, looping)

In [17]:
if 1<2:
    print("Hello")
elif 2<1:
    print("Bonjour")
else: 
    print("Bon dia")
print('end')
Hello
end
In [23]:
x=-2
if x>0:x
else:-x
Out[23]:
2
In [24]:
a,b=0,1
while a<2000:
    print(a,end=',')
    a,b=b,a+b
    
del a,b
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,

for in works on iterable objects.

In [ ]:
for i in range(40):
    print(i**2,end=", ")
In [25]:
try:  # whatever
    mytuple=(1,2,3)
    mytuple[1]=4
    
except TypeError:
    print("Type error.")

del mytuple  #  Executed even in case of error : cleaner exit.
Type error.
In [26]:
False and 1/0
Out[26]:
False

Procedural programming

Fibonacci
In [2]:
def Fibonacci(n):
    """Returns the Fibonacci sequence up to n-1 and returns last term."""
    a,b=0,1
    while a<n:
        print(a,end=',')
        a,b=b,a+b
    return a
        
Fibonacci(1598)

help(Fibonacci)

del Fibonacci
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,
Out[2]:
2584
Help on function Fibonacci in module __main__:

Fibonacci(n)
    Returns the Fibonacci sequence up to n-1 and returns last term.

yield returns a generator.

In [35]:
def Fibonacci_generator(n):
    a,b=0,1
    for _ in range(n):
        a,b=b,a+b
        yield b

for i in Fibonacci_generator(10):
    print(i,end=' ')

del Fibonacci_generator
1 2 3 5 8 13 21 34 55 89 
In [3]:
import random
def random_batch(n):
    i=0
    while i<n:
        i=i+1
        yield random.random()
In [31]:
list(random_batch(10))
Out[31]:
[0.431886241734323,
 0.933488867098474,
 0.6477278916882908,
 0.3122121908112484,
 0.5190567042538087,
 0.24637624431650174,
 0.3770290009027527,
 0.889859487091978,
 0.04466356294240348,
 0.9548867824383149]
In [34]:
iter1=iter(['a', 'e', 'i', 'o', 'u'])
for _ in range(5):
    next(iter1)
del iter1
Out[34]:
'a'
Out[34]:
'e'
Out[34]:
'i'
Out[34]:
'o'
Out[34]:
'u'

Remove trailing zeros

In [4]:
def removetrailingzeros(list1:list):
    while (len(list1)!=0) and (list1[-1]==0):
        list1=list1[:-1]
    return list1
In [37]:
list1=[0,1,0,1,0,0]
removetrailingzeros(list1)
list1
Out[37]:
[0, 1, 0, 1]
Out[37]:
[0, 1, 0, 1, 0, 0]
In [38]:
removetrailingzeros([0])
removetrailingzeros([])
Out[38]:
[]
Out[38]:
[]

Also works for tuple.

In [39]:
removetrailingzeros((1,1,0,0))
removetrailingzeros((0,))

removetrailingzeros(())
Out[39]:
(1, 1)
Out[39]:
()
Out[39]:
()

Programming techniques for clarity, generality and ease of maintenance

Centralize and protect information

Use constants (not easy in python):

In [42]:
from collections import namedtuple
In [43]:
constants=namedtuple('Constants', ['h', 'e'])(6.626e-34,1.60217e-19)
In [44]:
constants.e
Out[44]:
1.60217e-19
In [45]:
constants.e=1.6e-19 # fails
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-45-00686d300e11> in <module>()
----> 1 constants.e=1.6e-19

AttributeError: can't set attribute

Even if constants are not formally declared, avoid variable reaffectation.

In interactive use, restart kernel after any change, in order to determine initial conditions.

Care for namespaces

In [46]:
globals()
Out[46]:
{'In': ['',
  'from IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = "all"',
  'import random\ndef random_batch(n):\n    i=0\n    while i<n:\n        i=i+1\n        yield random.random()',
  'def removetrailingzeros(list1:list):\n    while (len(list1)!=0) and (list1[-1]==0):\n        list1=list1[:-1]\n    return list1',
  'class intvec():\n    """integer vector"""\n    def __init__(self,*tuple):\n        self.body=tuple\n        \n    def __repr__(self):\n        # string becomes automatically intvec \n        return \'intvec\'+str(self.body) \n    \n    def times(self,n:int):\n        """Multiply each sequence term by integer n."""\n        return intvec(*tuple(i*n for i in self.body))\n        \n    def add(self,*s1:tuple):\n        """Add to self, term by term."""\n        if len(self.body)>len(s1):\n            s1+=tuple(0 for i in range(len(self.body)-len(s1)))\n        elif len(self.body)<len(s1):\n            self.body+=tuple(0 for i in range(-len(self.body)+len(s1)))\n        self.body=tuple(self.body[i]+s1[i] for i in range(len(s1)))  \n        self.body=removetrailingzeros(self.body)\n        return intvec(*self.body)\n    \n    def __add__(self,iv1):\n    # def __add__(self,iv1:intvec): # intvec unknown here\n        """Overloads + for intvec."""\n        return intvec.add(self,*iv1.body)\n    \n    def __mul__(self,n:int):\n        """Overloads intvec*int."""\n        return intvec.times(self,n)\n    \n    def __rmul__(self,n:int): # int\n        """Overloads int*intvec."""\n        return intvec.__mul__(self,n)\n    \n        ',
  'import numpy',
  '# restart kernel\nimport Fibonacci',
  'Fibonacci.fib(10)',
  'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse\nprint("I said.")',
  'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse :\nprint("I said.")',
  'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse print("I said.")',
  'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse \nprint("I said.")',
  'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse: \n    print("I said.")',
  'if 1<0:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse: \n    print("I said.")',
  'if 1<0:\n    print("That is true.")\nelif 2<1:\n    print("That is false.")\nelse: \n    print("I said.")',
  'if 1<0:\n    print("Hello")\nelif 2<3:\n    print("Bonjour")\nelse: \n    print("Bon dia")\nprint(\'end\')',
  'if 1<0:\n    print("Hello")\nelif 2<1:\n    print("Bonjour")\nelse: \n    print("Bon dia")\nprint(\'end\')',
  'if 1<2:\n    print("Hello")\nelif 2<1:\n    print("Bonjour")\nelse: \n    print("Bon dia")\nprint(\'end\')',
  'x=-2\nif x>0:x \nelse:-x',
  'x=2\nif x>0:x \nelse:-x',
  'x=2\nif x>0:x else:-x',
  'x=2\nif x>0:x; else:-x',
  'x=2\nif x>0:x\nelse:-x',
  'x=-2\nif x>0:x\nelse:-x',
  "a,b=0,1\nwhile a<2000:\n    print(a,end=',')\n    a,b=b,a+b\n    \ndel a,b",
  'try:  # whatever\n    mytuple=(1,2,3)\n    mytuple[1]=4\n    \nexcept TypeError:\n    print("Type error.")\n\ndel mytuple  #  Executed even in case of error : cleaner exit.',
  'False and 1/0',
  'def Fibonacci(n):\n    """Returns the Fibonacci sequence up to n-1 and returns last term."""\n    a,b=0,1\n    while a<n:\n        print(a,end=\',\')\n        a,b=b,a+b\n    return a\n        \nFibonacci(1598)\n\nhelp(Fibonacci)\n\ndel Fibonacci',
  "def Fibonacci_generator(n):\n    a,b=0,1\n    for i in range(n):\n        a,b=b,a+b\n        yield b\n\nfor i in Fibonacci_generator(10):\n    print(i,end=' ')\n\ndel Fibonacci_generator",
  'import random\ndef random_batch(n):\n    i=0\n    while i<n:\n        i=i+1\n        yield random.random()',
  'import random\ndef random_batch(n):\n    i=0\n    while i<n:\n        i=i+1\n        yield random.random()',
  'list(random_batch(10))',
  "iter1=iter(['a', 'e', 'i', 'o', 'u'])\nfor i in range(5):\n    next(iter1)\ndel iter1",
  "iter1=iter(['a', 'e', 'i', 'o', 'u'])\nfor in range(5):\n    next(iter1)\ndel iter1",
  "iter1=iter(['a', 'e', 'i', 'o', 'u'])\nfor _ in range(5):\n    next(iter1)\ndel iter1",
  "def Fibonacci_generator(n):\n    a,b=0,1\n    for _ in range(n):\n        a,b=b,a+b\n        yield b\n\nfor i in Fibonacci_generator(10):\n    print(i,end=' ')\n\ndel Fibonacci_generator",
  'def removetrailingzeros(list1:list):\n    while (len(list1)!=0) and (list1[-1]==0):\n        list1=list1[:-1]\n    return list1',
  'list1=[0,1,0,1,0,0]\nremovetrailingzeros(list1)\nlist1',
  'removetrailingzeros([0])\nremovetrailingzeros([])',
  'removetrailingzeros((1,1,0,0))\nremovetrailingzeros((0,))\n\nremovetrailingzeros(())',
  '"""\nmultiple line\nembedded Python comment\n"""',
  '"""\nmultiple line\nembedded Python comment\n""";',
  'from collections import namedtuple',
  "constants=namedtuple('Constants', ['h', 'e'])(6.626e-34,1.60217e-19)",
  'constants.e',
  'constants.e=1.6e-19',
  'globals()'],
 'InteractiveShell': IPython.core.interactiveshell.InteractiveShell,
 'Out': {18: 2,
  19: 2,
  22: 2,
  23: 2,
  26: False,
  27: 2584,
  31: [0.431886241734323,
   0.933488867098474,
   0.6477278916882908,
   0.3122121908112484,
   0.5190567042538087,
   0.24637624431650174,
   0.3770290009027527,
   0.889859487091978,
   0.04466356294240348,
   0.9548867824383149],
  32: 'u',
  34: 'u',
  37: [0, 1, 0, 1, 0, 0],
  38: [],
  39: (),
  40: '\nmultiple line\nembedded Python comment\n',
  44: 1.60217e-19},
 '_': 1.60217e-19,
 '_18': 2,
 '_19': 2,
 '_22': 2,
 '_23': 2,
 '_26': False,
 '_27': 2584,
 '_31': [0.431886241734323,
  0.933488867098474,
  0.6477278916882908,
  0.3122121908112484,
  0.5190567042538087,
  0.24637624431650174,
  0.3770290009027527,
  0.889859487091978,
  0.04466356294240348,
  0.9548867824383149],
 '_32': 'u',
 '_34': 'u',
 '_37': [0, 1, 0, 1, 0, 0],
 '_38': [],
 '_39': (),
 '_40': '\nmultiple line\nembedded Python comment\n',
 '_44': 1.60217e-19,
 '__': '\nmultiple line\nembedded Python comment\n',
 '___': (),
 '__builtin__': <module 'builtins' (built-in)>,
 '__builtins__': <module 'builtins' (built-in)>,
 '__doc__': 'Automatically created module for IPython interactive environment',
 '__loader__': None,
 '__name__': '__main__',
 '__package__': None,
 '__spec__': None,
 '_dh': ['/Users/alba/Documents/technique/python'],
 '_i': 'constants.e=1.6e-19',
 '_i1': 'from IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = "all"',
 '_i10': 'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse print("I said.")',
 '_i11': 'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse \nprint("I said.")',
 '_i12': 'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse: \n    print("I said.")',
 '_i13': 'if 1<0:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse: \n    print("I said.")',
 '_i14': 'if 1<0:\n    print("That is true.")\nelif 2<1:\n    print("That is false.")\nelse: \n    print("I said.")',
 '_i15': 'if 1<0:\n    print("Hello")\nelif 2<3:\n    print("Bonjour")\nelse: \n    print("Bon dia")\nprint(\'end\')',
 '_i16': 'if 1<0:\n    print("Hello")\nelif 2<1:\n    print("Bonjour")\nelse: \n    print("Bon dia")\nprint(\'end\')',
 '_i17': 'if 1<2:\n    print("Hello")\nelif 2<1:\n    print("Bonjour")\nelse: \n    print("Bon dia")\nprint(\'end\')',
 '_i18': 'x=-2\nif x>0:x \nelse:-x',
 '_i19': 'x=2\nif x>0:x \nelse:-x',
 '_i2': 'import random\ndef random_batch(n):\n    i=0\n    while i<n:\n        i=i+1\n        yield random.random()',
 '_i20': 'x=2\nif x>0:x else:-x',
 '_i21': 'x=2\nif x>0:x; else:-x',
 '_i22': 'x=2\nif x>0:x\nelse:-x',
 '_i23': 'x=-2\nif x>0:x\nelse:-x',
 '_i24': "a,b=0,1\nwhile a<2000:\n    print(a,end=',')\n    a,b=b,a+b\n    \ndel a,b",
 '_i25': 'try:  # whatever\n    mytuple=(1,2,3)\n    mytuple[1]=4\n    \nexcept TypeError:\n    print("Type error.")\n\ndel mytuple  #  Executed even in case of error : cleaner exit.',
 '_i26': 'False and 1/0',
 '_i27': 'def Fibonacci(n):\n    """Returns the Fibonacci sequence up to n-1 and returns last term."""\n    a,b=0,1\n    while a<n:\n        print(a,end=\',\')\n        a,b=b,a+b\n    return a\n        \nFibonacci(1598)\n\nhelp(Fibonacci)\n\ndel Fibonacci',
 '_i28': "def Fibonacci_generator(n):\n    a,b=0,1\n    for i in range(n):\n        a,b=b,a+b\n        yield b\n\nfor i in Fibonacci_generator(10):\n    print(i,end=' ')\n\ndel Fibonacci_generator",
 '_i29': 'import random\ndef random_batch(n):\n    i=0\n    while i<n:\n        i=i+1\n        yield random.random()',
 '_i3': 'def removetrailingzeros(list1:list):\n    while (len(list1)!=0) and (list1[-1]==0):\n        list1=list1[:-1]\n    return list1',
 '_i30': 'import random\ndef random_batch(n):\n    i=0\n    while i<n:\n        i=i+1\n        yield random.random()',
 '_i31': 'list(random_batch(10))',
 '_i32': "iter1=iter(['a', 'e', 'i', 'o', 'u'])\nfor i in range(5):\n    next(iter1)\ndel iter1",
 '_i33': "iter1=iter(['a', 'e', 'i', 'o', 'u'])\nfor in range(5):\n    next(iter1)\ndel iter1",
 '_i34': "iter1=iter(['a', 'e', 'i', 'o', 'u'])\nfor _ in range(5):\n    next(iter1)\ndel iter1",
 '_i35': "def Fibonacci_generator(n):\n    a,b=0,1\n    for _ in range(n):\n        a,b=b,a+b\n        yield b\n\nfor i in Fibonacci_generator(10):\n    print(i,end=' ')\n\ndel Fibonacci_generator",
 '_i36': 'def removetrailingzeros(list1:list):\n    while (len(list1)!=0) and (list1[-1]==0):\n        list1=list1[:-1]\n    return list1',
 '_i37': 'list1=[0,1,0,1,0,0]\nremovetrailingzeros(list1)\nlist1',
 '_i38': 'removetrailingzeros([0])\nremovetrailingzeros([])',
 '_i39': 'removetrailingzeros((1,1,0,0))\nremovetrailingzeros((0,))\n\nremovetrailingzeros(())',
 '_i4': 'class intvec():\n    """integer vector"""\n    def __init__(self,*tuple):\n        self.body=tuple\n        \n    def __repr__(self):\n        # string becomes automatically intvec \n        return \'intvec\'+str(self.body) \n    \n    def times(self,n:int):\n        """Multiply each sequence term by integer n."""\n        return intvec(*tuple(i*n for i in self.body))\n        \n    def add(self,*s1:tuple):\n        """Add to self, term by term."""\n        if len(self.body)>len(s1):\n            s1+=tuple(0 for i in range(len(self.body)-len(s1)))\n        elif len(self.body)<len(s1):\n            self.body+=tuple(0 for i in range(-len(self.body)+len(s1)))\n        self.body=tuple(self.body[i]+s1[i] for i in range(len(s1)))  \n        self.body=removetrailingzeros(self.body)\n        return intvec(*self.body)\n    \n    def __add__(self,iv1):\n    # def __add__(self,iv1:intvec): # intvec unknown here\n        """Overloads + for intvec."""\n        return intvec.add(self,*iv1.body)\n    \n    def __mul__(self,n:int):\n        """Overloads intvec*int."""\n        return intvec.times(self,n)\n    \n    def __rmul__(self,n:int): # int\n        """Overloads int*intvec."""\n        return intvec.__mul__(self,n)\n    \n        ',
 '_i40': '"""\nmultiple line\nembedded Python comment\n"""',
 '_i41': '"""\nmultiple line\nembedded Python comment\n""";',
 '_i42': 'from collections import namedtuple',
 '_i43': "constants=namedtuple('Constants', ['h', 'e'])(6.626e-34,1.60217e-19)",
 '_i44': 'constants.e',
 '_i45': 'constants.e=1.6e-19',
 '_i46': 'globals()',
 '_i5': 'import numpy',
 '_i6': '# restart kernel\nimport Fibonacci',
 '_i7': 'Fibonacci.fib(10)',
 '_i8': 'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse\nprint("I said.")',
 '_i9': 'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse :\nprint("I said.")',
 '_ih': ['',
  'from IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = "all"',
  'import random\ndef random_batch(n):\n    i=0\n    while i<n:\n        i=i+1\n        yield random.random()',
  'def removetrailingzeros(list1:list):\n    while (len(list1)!=0) and (list1[-1]==0):\n        list1=list1[:-1]\n    return list1',
  'class intvec():\n    """integer vector"""\n    def __init__(self,*tuple):\n        self.body=tuple\n        \n    def __repr__(self):\n        # string becomes automatically intvec \n        return \'intvec\'+str(self.body) \n    \n    def times(self,n:int):\n        """Multiply each sequence term by integer n."""\n        return intvec(*tuple(i*n for i in self.body))\n        \n    def add(self,*s1:tuple):\n        """Add to self, term by term."""\n        if len(self.body)>len(s1):\n            s1+=tuple(0 for i in range(len(self.body)-len(s1)))\n        elif len(self.body)<len(s1):\n            self.body+=tuple(0 for i in range(-len(self.body)+len(s1)))\n        self.body=tuple(self.body[i]+s1[i] for i in range(len(s1)))  \n        self.body=removetrailingzeros(self.body)\n        return intvec(*self.body)\n    \n    def __add__(self,iv1):\n    # def __add__(self,iv1:intvec): # intvec unknown here\n        """Overloads + for intvec."""\n        return intvec.add(self,*iv1.body)\n    \n    def __mul__(self,n:int):\n        """Overloads intvec*int."""\n        return intvec.times(self,n)\n    \n    def __rmul__(self,n:int): # int\n        """Overloads int*intvec."""\n        return intvec.__mul__(self,n)\n    \n        ',
  'import numpy',
  '# restart kernel\nimport Fibonacci',
  'Fibonacci.fib(10)',
  'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse\nprint("I said.")',
  'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse :\nprint("I said.")',
  'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse print("I said.")',
  'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse \nprint("I said.")',
  'if 1<2:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse: \n    print("I said.")',
  'if 1<0:\n    print("That is true.")\nelif 2<3:\n    print("That is false.")\nelse: \n    print("I said.")',
  'if 1<0:\n    print("That is true.")\nelif 2<1:\n    print("That is false.")\nelse: \n    print("I said.")',
  'if 1<0:\n    print("Hello")\nelif 2<3:\n    print("Bonjour")\nelse: \n    print("Bon dia")\nprint(\'end\')',
  'if 1<0:\n    print("Hello")\nelif 2<1:\n    print("Bonjour")\nelse: \n    print("Bon dia")\nprint(\'end\')',
  'if 1<2:\n    print("Hello")\nelif 2<1:\n    print("Bonjour")\nelse: \n    print("Bon dia")\nprint(\'end\')',
  'x=-2\nif x>0:x \nelse:-x',
  'x=2\nif x>0:x \nelse:-x',
  'x=2\nif x>0:x else:-x',
  'x=2\nif x>0:x; else:-x',
  'x=2\nif x>0:x\nelse:-x',
  'x=-2\nif x>0:x\nelse:-x',
  "a,b=0,1\nwhile a<2000:\n    print(a,end=',')\n    a,b=b,a+b\n    \ndel a,b",
  'try:  # whatever\n    mytuple=(1,2,3)\n    mytuple[1]=4\n    \nexcept TypeError:\n    print("Type error.")\n\ndel mytuple  #  Executed even in case of error : cleaner exit.',
  'False and 1/0',
  'def Fibonacci(n):\n    """Returns the Fibonacci sequence up to n-1 and returns last term."""\n    a,b=0,1\n    while a<n:\n        print(a,end=\',\')\n        a,b=b,a+b\n    return a\n        \nFibonacci(1598)\n\nhelp(Fibonacci)\n\ndel Fibonacci',
  "def Fibonacci_generator(n):\n    a,b=0,1\n    for i in range(n):\n        a,b=b,a+b\n        yield b\n\nfor i in Fibonacci_generator(10):\n    print(i,end=' ')\n\ndel Fibonacci_generator",
  'import random\ndef random_batch(n):\n    i=0\n    while i<n:\n        i=i+1\n        yield random.random()',
  'import random\ndef random_batch(n):\n    i=0\n    while i<n:\n        i=i+1\n        yield random.random()',
  'list(random_batch(10))',
  "iter1=iter(['a', 'e', 'i', 'o', 'u'])\nfor i in range(5):\n    next(iter1)\ndel iter1",
  "iter1=iter(['a', 'e', 'i', 'o', 'u'])\nfor in range(5):\n    next(iter1)\ndel iter1",
  "iter1=iter(['a', 'e', 'i', 'o', 'u'])\nfor _ in range(5):\n    next(iter1)\ndel iter1",
  "def Fibonacci_generator(n):\n    a,b=0,1\n    for _ in range(n):\n        a,b=b,a+b\n        yield b\n\nfor i in Fibonacci_generator(10):\n    print(i,end=' ')\n\ndel Fibonacci_generator",
  'def removetrailingzeros(list1:list):\n    while (len(list1)!=0) and (list1[-1]==0):\n        list1=list1[:-1]\n    return list1',
  'list1=[0,1,0,1,0,0]\nremovetrailingzeros(list1)\nlist1',
  'removetrailingzeros([0])\nremovetrailingzeros([])',
  'removetrailingzeros((1,1,0,0))\nremovetrailingzeros((0,))\n\nremovetrailingzeros(())',
  '"""\nmultiple line\nembedded Python comment\n"""',
  '"""\nmultiple line\nembedded Python comment\n""";',
  'from collections import namedtuple',
  "constants=namedtuple('Constants', ['h', 'e'])(6.626e-34,1.60217e-19)",
  'constants.e',
  'constants.e=1.6e-19',
  'globals()'],
 '_ii': 'constants.e',
 '_iii': "constants=namedtuple('Constants', ['h', 'e'])(6.626e-34,1.60217e-19)",
 '_oh': {18: 2,
  19: 2,
  22: 2,
  23: 2,
  26: False,
  27: 2584,
  31: [0.431886241734323,
   0.933488867098474,
   0.6477278916882908,
   0.3122121908112484,
   0.5190567042538087,
   0.24637624431650174,
   0.3770290009027527,
   0.889859487091978,
   0.04466356294240348,
   0.9548867824383149],
  32: 'u',
  34: 'u',
  37: [0, 1, 0, 1, 0, 0],
  38: [],
  39: (),
  40: '\nmultiple line\nembedded Python comment\n',
  44: 1.60217e-19},
 '_sh': <module 'IPython.core.shadowns' from '/Users/alba/anaconda3/lib/python3.6/site-packages/IPython/core/shadowns.py'>,
 'constants': Constants(h=6.626e-34, e=1.60217e-19),
 'exit': <IPython.core.autocall.ZMQExitAutocall at 0x108b724a8>,
 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x108b62e80>>,
 'i': 89,
 'intvec': __main__.intvec,
 'list1': [0, 1, 0, 1, 0, 0],
 'namedtuple': <function collections.namedtuple>,
 'numpy': <module 'numpy' from '/Users/alba/anaconda3/lib/python3.6/site-packages/numpy/__init__.py'>,
 'pi': 3.141592653,
 'quit': <IPython.core.autocall.ZMQExitAutocall at 0x108b724a8>,
 'random': <module 'random' from '/Users/alba/anaconda3/lib/python3.6/random.py'>,
 'random_batch': <function __main__.random_batch>,
 'removetrailingzeros': <function __main__.removetrailingzeros>,
 'x': -2}
In [47]:
def function1(x):
    print("Hello",x)
    y=2
    print(locals())
function1("Robert")
del function1
Hello Robert
{'y': 2, 'x': 'Robert'}

for in uses no global variable.

In [ ]:
del i
for i in range(3):pass
i

while may use a global variable:

In [ ]:
i=0
while i<10:print(i);i+=1
i

From the tutorial:

In [49]:
def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"
        
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)
    
scope_test()
print("In global scope:", spam)
del spam, scope_test
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

Are function calls by value or reference? It depends.

Calling on an immutable object is equivalent to calling by value, as any change on the object in the function will create a new local object with the same name, not visible ouside the function.

In [48]:
def ref_demo(x):
    print(x," id=",id(x))
    x=42
    print(x," id=",id(x))
x=9
ref_demo(x) 
x
id(x)
del ref_demo
9  id= 4415981824
42  id= 4415982880
Out[48]:
9
Out[48]:
4415981824

Calling on a mutable object is equivalent to calling by reference, as any change on the object in the function will be visible outside the function.

In [50]:
l1=[1,2,3] 

id(l1)

def ref_demo1(x):
    print(x," id=",id(x))
    x[-1]=42
    print(x," id=",id(x))

ref_demo1(l1)

l1

id(l1)
Out[50]:
4537834632
[1, 2, 3]  id= 4537834632
[1, 2, 42]  id= 4537834632
Out[50]:
[1, 2, 42]
Out[50]:
4537834632

del removes but does not restore variables. The global namespace can be really protected by calling a function and working with its local variables:

In [ ]:
x=1;y=2  # to be protected
def module():
    x=17  # local
    y=18
    z=19
    print(x,y)
module()
x
y
del module,x,y
z

Of course, module was touched, but if it is conventionally reserved for this use, the harm is contained.

Scripts or modules run by default with their own namespaces, just like functions, except for from import *.

Use pure functions and check argument compatibility

Pure functions are procedures that work like the mathematical or black box model x -> f(x), without implicit dependence (hidden input) or side effect (hidden output).

For example random has hidden dependences on a seed, so that it is not a pure function (as long as the seed is not explicited as argument). On the contrary, Fibonacci is a pure function

Pure functions can be debugged by simply running them on many arguments. They do not touch the caller namespace.

Programming implies using classes and functions together. They ought to be compatible. There are basically two ways to check that.

  • Functional programming: for every function, determine possible argument classes, with pattern matching or tests. Hence, classes are grouped under functions.
  • Object programming: for every class, determine possible functions. Hence, functions are grouped under classes.

Unfortunately, python has been developped mostly in the intention of object programming.

Functional programming

It happens that programming without variable is always possible. It is functional programming. All functions are certainly pure if no variable is used. Constant names are still used to bring sense. A meaningless name, like i, x, should only be used as a dummy name (not refering to anything).

See this more detailed presentation: https://docs.python.org/3.6/howto/functional.html.

λ-expressions

They represent anonymous functions (except for the generic name λ).

In [52]:
(lambda x:x**2)(10) # dummy x
Out[52]:
100
In [53]:
(lambda x:x[0]+x[1])([10,11])
Out[53]:
21

λ-expression for a diadic function:

In [54]:
(lambda x,y:x+y)(10,11)
Out[54]:
21

List manipulation

Unpacking (iterable objects) avoids some variables.

In [55]:
def diadic(x,y): 
    print(x,y)

try:    
    diadic([1,2]) 
except TypeError:
    print("Type error.")

x,y=[1,2]
diadic(x,y)
del x,y

diadic(*[1,2]) # Unpacking does the same as above without variables.

diadic(*(1,2))

del diadic
Type error.
1 2
1 2
1 2
In [57]:
list(range(*[1,10]))
Out[57]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Table (functional loop)

In [61]:
[x**2 for x in range(10)]
Out[61]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [62]:
(x**2 for x in range(10))
Out[62]:
<generator object <genexpr> at 0x10e736888>

Map

In [66]:
list(map(lambda x:x**2,range(10)))
Out[66]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

zip

In [67]:
list(zip([1,2,3],[3,4,5]))
list(zip((1,2,3),(3,4,5)))
Out[67]:
[(1, 3), (2, 4), (3, 5)]
Out[67]:
[(1, 3), (2, 4), (3, 5)]

Inner product

This is not functional programming because there is one variable:

In [68]:
x=[1,4,2]
sum(x[i]*[5,6,2][i] for i in range(len(x)))
del x
Out[68]:
33

This is functional programming:

In [ ]:
sum(map(lambda x:x[0]*x[1],zip([1,4,2],[5,6,2])))
In [ ]:
list(zip(["1","2","3"],['a','b','c']))
In [ ]:
?zip
In [ ]:
list(map(lambda x:'times('+str(x[0])+', '+str(x[1]+')'),zip(["1","2","3"],['a','b','c'])))

Outer product

In [69]:
[['fun('+str(x)+', '+str(y)+')' for y in [1,2,3]] for x in [3,1,4]]
Out[69]:
[['fun(3, 1)', 'fun(3, 2)', 'fun(3, 3)'],
 ['fun(1, 1)', 'fun(1, 2)', 'fun(1, 3)'],
 ['fun(4, 1)', 'fun(4, 2)', 'fun(4, 3)']]

Tests

if else and try except do not have a functional form but this can be repaired.

In [70]:
def fif(x,tc,fc):
    if x:
        #print("True")
        return tc
    else:
        #print("False")
        return fc
In [71]:
fabs=(lambda x:fif(x>0,x,-x))

fpos=(lambda x:fif(x>0,x,0))

fneg=(lambda x:fif(x>0,0,-x))

x=-3
fabs(x)
fpos(x)
fneg(x)
Out[71]:
3
Out[71]:
0
Out[71]:
3
In [72]:
fpos(x)+fneg(x)==fabs(x)

fpos(x)-fneg(x)==x
Out[72]:
True
Out[72]:
True
In [73]:
help(filter)
Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

In [74]:
list(filter((lambda x:type(x)==str),["w",(1),[2]]))
Out[74]:
['w']

Pattern matching, substitution rules

In [75]:
def function1(x:float,y:int)->float:
    return x**(1/y)
In [78]:
help(function1)
Help on function function1 in module __main__:

function1(x:float, y:int) -> float

Argument class specification are just for the documentation, not actual filtering.

In [79]:
function1(4.,2)
function1(4,2.)
Out[79]:
2.0
Out[79]:
2.0

python cannot in general hold any expression, search for patterns and replace, but it can do it on strings.

In [80]:
import re
help(re)
Help on module re:

NAME
    re - Support for regular expressions (RE).

MODULE REFERENCE
    https://docs.python.org/3.6/library/re
    
    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 regular expression matching operations similar to
    those found in Perl.  It supports both 8-bit and Unicode strings; both
    the pattern and the strings being processed can contain null bytes and
    characters outside the US ASCII range.
    
    Regular expressions can contain both special and ordinary characters.
    Most ordinary characters, like "A", "a", or "0", are the simplest
    regular expressions; they simply match themselves.  You can
    concatenate ordinary characters, so last matches the string 'last'.
    
    The special characters are:
        "."      Matches any character except a newline.
        "^"      Matches the start of the string.
        "$"      Matches the end of the string or just before the newline at
                 the end of the string.
        "*"      Matches 0 or more (greedy) repetitions of the preceding RE.
                 Greedy means that it will match as many repetitions as possible.
        "+"      Matches 1 or more (greedy) repetitions of the preceding RE.
        "?"      Matches 0 or 1 (greedy) of the preceding RE.
        *?,+?,?? Non-greedy versions of the previous three special characters.
        {m,n}    Matches from m to n repetitions of the preceding RE.
        {m,n}?   Non-greedy version of the above.
        "\\"     Either escapes special characters or signals a special sequence.
        []       Indicates a set of characters.
                 A "^" as the first character indicates a complementing set.
        "|"      A|B, creates an RE that will match either A or B.
        (...)    Matches the RE inside the parentheses.
                 The contents can be retrieved or matched later in the string.
        (?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below).
        (?:...)  Non-grouping version of regular parentheses.
        (?P<name>...) The substring matched by the group is accessible by name.
        (?P=name)     Matches the text matched earlier by the group named name.
        (?#...)  A comment; ignored.
        (?=...)  Matches if ... matches next, but doesn't consume the string.
        (?!...)  Matches if ... doesn't match next.
        (?<=...) Matches if preceded by ... (must be fixed length).
        (?<!...) Matches if not preceded by ... (must be fixed length).
        (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,
                           the (optional) no pattern otherwise.
    
    The special sequences consist of "\\" and a character from the list
    below.  If the ordinary character is not on the list, then the
    resulting RE will match the second character.
        \number  Matches the contents of the group of the same number.
        \A       Matches only at the start of the string.
        \Z       Matches only at the end of the string.
        \b       Matches the empty string, but only at the start or end of a word.
        \B       Matches the empty string, but not at the start or end of a word.
        \d       Matches any decimal digit; equivalent to the set [0-9] in
                 bytes patterns or string patterns with the ASCII flag.
                 In string patterns without the ASCII flag, it will match the whole
                 range of Unicode digits.
        \D       Matches any non-digit character; equivalent to [^\d].
        \s       Matches any whitespace character; equivalent to [ \t\n\r\f\v] in
                 bytes patterns or string patterns with the ASCII flag.
                 In string patterns without the ASCII flag, it will match the whole
                 range of Unicode whitespace characters.
        \S       Matches any non-whitespace character; equivalent to [^\s].
        \w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]
                 in bytes patterns or string patterns with the ASCII flag.
                 In string patterns without the ASCII flag, it will match the
                 range of Unicode alphanumeric characters (letters plus digits
                 plus underscore).
                 With LOCALE, it will match the set [0-9_] plus characters defined
                 as letters for the current locale.
        \W       Matches the complement of \w.
        \\       Matches a literal backslash.
    
    This module exports the following functions:
        match     Match a regular expression pattern to the beginning of a string.
        fullmatch Match a regular expression pattern to all of a string.
        search    Search a string for the presence of a pattern.
        sub       Substitute occurrences of a pattern found in a string.
        subn      Same as sub, but also return the number of substitutions made.
        split     Split a string by the occurrences of a pattern.
        findall   Find all occurrences of a pattern in a string.
        finditer  Return an iterator yielding a match object for each match.
        compile   Compile a pattern into a RegexObject.
        purge     Clear the regular expression cache.
        escape    Backslash all non-alphanumerics in a string.
    
    Some of the functions in this module takes flags as optional parameters:
        A  ASCII       For string patterns, make \w, \W, \b, \B, \d, \D
                       match the corresponding ASCII character categories
                       (rather than the whole Unicode categories, which is the
                       default).
                       For bytes patterns, this flag is the only available
                       behaviour and needn't be specified.
        I  IGNORECASE  Perform case-insensitive matching.
        L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.
        M  MULTILINE   "^" matches the beginning of lines (after a newline)
                       as well as the string.
                       "$" matches the end of lines (before a newline) as well
                       as the end of the string.
        S  DOTALL      "." matches any character at all, including the newline.
        X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.
        U  UNICODE     For compatibility only. Ignored for string patterns (it
                       is the default), and forbidden for bytes patterns.
    
    This module also defines an exception 'error'.

CLASSES
    builtins.Exception(builtins.BaseException)
        sre_constants.error
    
    class error(builtins.Exception)
     |  Common base class for all non-exit exceptions.
     |  
     |  Method resolution order:
     |      error
     |      builtins.Exception
     |      builtins.BaseException
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, msg, pattern=None, pos=None)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.Exception:
     |  
     |  __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
    compile(pattern, flags=0)
        Compile a regular expression pattern, returning a pattern object.
    
    escape(pattern)
        Escape all the characters in pattern except ASCII letters, numbers and '_'.
    
    findall(pattern, string, flags=0)
        Return a list of all non-overlapping matches in the string.
        
        If one or more capturing groups are present in the pattern, return
        a list of groups; this will be a list of tuples if the pattern
        has more than one group.
        
        Empty matches are included in the result.
    
    finditer(pattern, string, flags=0)
        Return an iterator over all non-overlapping matches in the
        string.  For each match, the iterator returns a match object.
        
        Empty matches are included in the result.
    
    fullmatch(pattern, string, flags=0)
        Try to apply the pattern to all of the string, returning
        a match object, or None if no match was found.
    
    match(pattern, string, flags=0)
        Try to apply the pattern at the start of the string, returning
        a match object, or None if no match was found.
    
    purge()
        Clear the regular expression caches
    
    search(pattern, string, flags=0)
        Scan through string looking for a match to the pattern, returning
        a match object, or None if no match was found.
    
    split(pattern, string, maxsplit=0, flags=0)
        Split the source string by the occurrences of the pattern,
        returning a list containing the resulting substrings.  If
        capturing parentheses are used in pattern, then the text of all
        groups in the pattern are also returned as part of the resulting
        list.  If maxsplit is nonzero, at most maxsplit splits occur,
        and the remainder of the string is returned as the final element
        of the list.
    
    sub(pattern, repl, string, count=0, flags=0)
        Return the string obtained by replacing the leftmost
        non-overlapping occurrences of the pattern in string by the
        replacement repl.  repl can be either a string or a callable;
        if a string, backslash escapes in it are processed.  If it is
        a callable, it's passed the match object and must return
        a replacement string to be used.
    
    subn(pattern, repl, string, count=0, flags=0)
        Return a 2-tuple containing (new_string, number).
        new_string is the string obtained by replacing the leftmost
        non-overlapping occurrences of the pattern in the source
        string by the replacement repl.  number is the number of
        substitutions that were made. repl can be either a string or a
        callable; if a string, backslash escapes in it are processed.
        If it is a callable, it's passed the match object and must
        return a replacement string to be used.
    
    template(pattern, flags=0)
        Compile a template pattern, returning a pattern object

DATA
    A = <RegexFlag.ASCII: 256>
    ASCII = <RegexFlag.ASCII: 256>
    DOTALL = <RegexFlag.DOTALL: 16>
    I = <RegexFlag.IGNORECASE: 2>
    IGNORECASE = <RegexFlag.IGNORECASE: 2>
    L = <RegexFlag.LOCALE: 4>
    LOCALE = <RegexFlag.LOCALE: 4>
    M = <RegexFlag.MULTILINE: 8>
    MULTILINE = <RegexFlag.MULTILINE: 8>
    S = <RegexFlag.DOTALL: 16>
    U = <RegexFlag.UNICODE: 32>
    UNICODE = <RegexFlag.UNICODE: 32>
    VERBOSE = <RegexFlag.VERBOSE: 64>
    X = <RegexFlag.VERBOSE: 64>
    __all__ = ['match', 'fullmatch', 'search', 'sub', 'subn', 'split', 'fi...

VERSION
    2.2.1

FILE
    /Users/alba/anaconda3/lib/python3.6/re.py


In [82]:
re.match(r".*o.*","bob")

re.sub(r"b(.)b","X","bobaobab")
Out[82]:
<_sre.SRE_Match object; span=(0, 3), match='bob'>
Out[82]:
'XaoX'

Object programming

"Every object has an identity, a type [class] and a value."

In [83]:
list1=list(range(5))
list1
list1.copy() is list1.copy()
type(list1)
dir(list1)
del list1
Out[83]:
[0, 1, 2, 3, 4]
Out[83]:
False
Out[83]:
list
Out[83]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']
In [86]:
dir(1000)
Out[86]:
['__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__',
 'bit_length',
 'conjugate',
 'denominator',
 'from_bytes',
 'imag',
 'numerator',
 'real',
 'to_bytes']
In [84]:
1000 is 10**3
Out[84]:
False

Class

In [87]:
class object:
    pass
In [88]:
Robert=object()
Robert.weight=80;
Robert.birthdate="19120401";
In [89]:
dir(Robert)
Out[89]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'birthdate',
 'weight']
In [90]:
Robert.weight
Robert.birthdate
Out[90]:
80
Out[90]:
'19120401'

Object programming can make an immutable change (from Jeff Knupp).

In [ ]:
class Foo():
    def __init__(self):
        self.value = 10
#    def __str__(self):
#        return str(self.value)
    def __repr__(self):
        return str(self.value)

f=Foo()

f
print(f)
str(f)

tuple1=[f]  # tuple1 is bound to f
tuple1

f.value=0   
tuple1  # tuple1 is still bound to f but f has changed behind the scene

del Foo,f,tuple1

See also https://docs.python.org/3/reference/datamodel.html#types "An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.)"

In [91]:
class Fibonacci:
    """Fibonacci sequence"""
    datecreated = "20170622"
    
    def __init__(self,a:int,b:int):
        self.first = a
        self.second = b
        self.body = [a, b]
        
    def grow(self,n:int=1):
        """Appends n elements to Fibonacci sequence, n≥0."""
        if not isinstance(n, int):
            raise TypeError
        i=0
        while i<n:
            i+=1
            self.body.append(self.body[-1]+self.body[-2])
In [92]:
help(Fibonacci)
dir(Fibonacci)
Help on class Fibonacci in module __main__:

class Fibonacci(builtins.object)
 |  Fibonacci sequence
 |  
 |  Methods defined here:
 |  
 |  __init__(self, a:int, b:int)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  grow(self, n:int=1)
 |      Appends n elements to Fibonacci sequence, n≥0.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  datecreated = '20170622'

Out[92]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'datecreated',
 'grow']
In [93]:
Fibonacci.datecreated
Fibonacci.__dict__
Out[93]:
'20170622'
Out[93]:
mappingproxy({'__dict__': <attribute '__dict__' of 'Fibonacci' objects>,
              '__doc__': 'Fibonacci sequence',
              '__init__': <function __main__.Fibonacci.__init__>,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'Fibonacci' objects>,
              'datecreated': '20170622',
              'grow': <function __main__.Fibonacci.grow>})
In [94]:
s1=Fibonacci(5,8)
type(s1)
Out[94]:
__main__.Fibonacci
In [95]:
s1.first
s1.second
s1.body
Out[95]:
5
Out[95]:
8
Out[95]:
[5, 8]
In [96]:
s1.grow(4)
s1.body
Out[96]:
[5, 8, 13, 21, 34, 55]
In [99]:
s1=Fibonacci(5,10)
Fibonacci.grow(s1,1)
s1.body

s1=Fibonacci(5,10)
s1.grow(1)
s1.body
Out[99]:
[5, 10, 15]
Out[99]:
[5, 10, 15]

From the tutorial "All attributes of a class that are function objects define corresponding methods of its instances."

In [97]:
Fibonacci.grow
Out[97]:
<function __main__.Fibonacci.grow>
In [98]:
s1.grow
Out[98]:
<bound method Fibonacci.grow of <__main__.Fibonacci object at 0x10e7b3c88>>
In [100]:
s1.grow.__class__
Out[100]:
method
In [101]:
type(s1.grow)
Out[101]:
method
In [106]:
dir(s1.grow)
Out[106]:
['__call__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__func__',
 '__ge__',
 '__get__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__self__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__']
In [107]:
s1.grow.__self__
s1.grow.__func__
s1.grow.__doc__
s1.grow.__module__
Out[107]:
<__main__.Fibonacci at 0x10e7b95f8>
Out[107]:
<function __main__.Fibonacci.grow>
Out[107]:
'Appends n elements to Fibonacci sequence, n≥0.'
Out[107]:
'__main__'
In [103]:
s1.datecreated
Out[103]:
'20170622'
In [104]:
Fibonacci.datecreated
Out[104]:
'20170622'

Inheritance, overloading

In [108]:
class couple(tuple):
    pass
In [109]:
couple1=couple((1,2))
len(couple1)
1 in couple1
couple1[-1]
Out[109]:
2
Out[109]:
True
Out[109]:
2
In [110]:
class couple(tuple):
    def __init__(self,tuple):
        if len(tuple)==2:
            self=tuple
        else:
            print("Error: a couple must have two elements.")
In [112]:
couple1=couple((1,2))
couple1
Out[112]:
(1, 2)
In [113]:
couple((1,2,3))
Error: a couple must have two elements.
Out[113]:
(1, 2, 3)

intvec: integer vectors, makes a module on ring Z.

In [5]:
class intvec():
    """integer vector"""
    def __init__(self,*tuple):
        self.body=tuple
        
    def __repr__(self):
        # string becomes automatically intvec 
        return 'intvec'+str(self.body) 
    
    def times(self,n:int):
        """Multiply each sequence term by integer n."""
        return intvec(*tuple(i*n for i in self.body))
        
    def add(self,*s1:tuple):
        """Add to self, term by term."""
        if len(self.body)>len(s1):
            s1+=tuple(0 for i in range(len(self.body)-len(s1)))
        elif len(self.body)<len(s1):
            self.body+=tuple(0 for i in range(-len(self.body)+len(s1)))
        self.body=tuple(self.body[i]+s1[i] for i in range(len(s1)))  
        self.body=removetrailingzeros(self.body)
        return intvec(*self.body)
    
    def __add__(self,iv1):
    # def __add__(self,iv1:intvec): # intvec unknown here
        """Overloads + for intvec."""
        return intvec.add(self,*iv1.body)
    
    def __mul__(self,n:int):
        """Overloads intvec*int."""
        return intvec.times(self,n)
    
    def __rmul__(self,n:int): # int
        """Overloads int*intvec."""
        return intvec.__mul__(self,n)
    
        
In [116]:
intvec(1,2).body

intvec(1,2).times(3)
Out[116]:
(1, 2)
Out[116]:
intvec(3, 6)
In [117]:
intvec(1,2).add(2,1)
intvec(1,2).add(-1,-2)


s1=intvec(1,2)
s1.add(1,1,1)
s1

s1.add(1).add(0,0,0,0,0,1)
Out[117]:
intvec(3, 3)
Out[117]:
intvec()
Out[117]:
intvec(2, 3, 1)
Out[117]:
intvec(2, 3, 1)
Out[117]:
intvec(3, 3, 1, 0, 0, 1)
In [118]:
intvec(1,2)+intvec(2,1)

intvec(4,3,-4)*-3
Out[118]:
intvec(3, 3)
Out[118]:
intvec(-12, -9, 12)

The integer factor can also lay before.

In [119]:
3*intvec(1)
Out[119]:
intvec(3,)

The sum of Fibonacci sequences also is a Fibonacci sequence. Fibonacci sequences are a subclas of intvec.

In [120]:
class Fib(intvec):
# class Fibonacci:
    """Fibonacci intvec sequence"""

    """ def __init__(self,a:int,b:int):
        self.first = a
        self.second = b
        self.body = [a, b]
    """

        
    def grow(self,n:int=1):
        """Appends n elements to Fibonacci sequence, n≥0."""
        if not isinstance(n, int):
            raise TypeError
        i=0
        while i<n:
            i+=1
            self.body+=(self.body[-1]+self.body[-2],)
        return Fib(*self.body)
In [121]:
s1=Fib(1,2).grow(4)
s2=Fib(1,-1).grow(4)

s1
s2

s1+s2
Out[121]:
intvec(1, 2, 3, 5, 8, 13)
Out[121]:
intvec(1, -1, 0, -1, -1, -2)
Out[121]:
intvec(2, 1, 3, 4, 7, 11)

WRONG: when summing unequal length Fib : shorter Fib should not be completed with trailing zeros but grown according to Fib method. There are many ways to complete a sequence…

In [122]:
s1=Fib(1,2)
s2=Fib(1,-1).grow(4)

s1
s2

s1+s2
Out[122]:
intvec(1, 2)
Out[122]:
intvec(1, -1, 0, -1, -1, -2)
Out[122]:
intvec(2, 1, 0, -1, -1, -2)

Communication

Email, web browser

In [123]:
import smtplib
In [124]:
server=smtplib.SMTP('smtp.orange.fr')
In [125]:
help(server.sendmail)
Help on method sendmail in module smtplib:

sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[]) method of smtplib.SMTP instance
    This command performs an entire mail transaction.
    
    The arguments are:
        - from_addr    : The address sending this mail.
        - to_addrs     : A list of addresses to send this mail to.  A bare
                         string will be treated as a list with 1 address.
        - msg          : The message to send.
        - mail_options : List of ESMTP options (such as 8bitmime) for the
                         mail command.
        - rcpt_options : List of ESMTP options (such as DSN commands) for
                         all the rcpt commands.
    
    msg may be a string containing characters in the ASCII range, or a byte
    string.  A string is encoded to bytes using the ascii codec, and lone
    \r and \n characters are converted to \r\n characters.
    
    If there has been no previous EHLO or HELO command this session, this
    method tries ESMTP EHLO first.  If the server does ESMTP, message size
    and each of the specified options will be passed to it.  If EHLO
    fails, HELO will be tried and ESMTP options suppressed.
    
    This method will return normally if the mail is accepted for at least
    one recipient.  It returns a dictionary, with one entry for each
    recipient that was refused.  Each entry contains a tuple of the SMTP
    error code and the accompanying error message sent by the server.
    
    This method may raise the following exceptions:
    
     SMTPHeloError          The server didn't reply properly to
                            the helo greeting.
     SMTPRecipientsRefused  The server rejected ALL recipients
                            (no mail was sent).
     SMTPSenderRefused      The server didn't accept the from_addr.
     SMTPDataError          The server replied with an unexpected
                            error code (other than a refusal of
                            a recipient).
     SMTPNotSupportedError  The mail_options parameter includes 'SMTPUTF8'
                            but the SMTPUTF8 extension is not supported by
                            the server.
    
    Note: the connection will be open even after an exception is raised.
    
    Example:
    
     >>> import smtplib
     >>> s=smtplib.SMTP("localhost")
     >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
     >>> msg = '''\
     ... From: Me@my.org
     ... Subject: testin'...
     ...
     ... This is a test '''
     >>> s.sendmail("me@my.org",tolist,msg)
     { "three@three.org" : ( 550 ,"User unknown" ) }
     >>> s.quit()
    
    In the above example, the message was accepted for delivery to three
    of the four addresses, and one was rejected, with the error code
    550.  If all addresses are accepted, then the method will return an
    empty dictionary.

In [126]:
msg='''\
From: xxx.albarede@orange.fr
To: yyy.albarede@free.fr
Subject: calcul termine

test 1900'''

print(msg)
From: xxx.albarede@orange.fr
To: yyy.albarede@free.fr
Subject: calcul termine

test 1900
In [127]:
server.sendmail('any.body@free.fr','pierre.albarede@free.fr',msg)
Out[127]:
{}
In [128]:
del server
In [129]:
import webbrowser

# Page will open in a new tab.
webbrowser.open("https://docs.python.org/3.6/tutorial/")
Out[129]:
True

ftp client ?

Data sets

Install if needed.

In [42]:
!pip install pydataset
Requirement already satisfied: pydataset in /Users/alba/anaconda3/lib/python3.6/site-packages
Requirement already satisfied: pandas in /Users/alba/anaconda3/lib/python3.6/site-packages (from pydataset)
Requirement already satisfied: python-dateutil>=2 in /Users/alba/anaconda3/lib/python3.6/site-packages (from pandas->pydataset)
Requirement already satisfied: pytz>=2011k in /Users/alba/anaconda3/lib/python3.6/site-packages (from pandas->pydataset)
Requirement already satisfied: numpy>=1.7.0 in /Users/alba/anaconda3/lib/python3.6/site-packages (from pandas->pydataset)
Requirement already satisfied: six>=1.5 in /Users/alba/anaconda3/lib/python3.6/site-packages (from python-dateutil>=2->pandas->pydataset)
In [130]:
from pydataset import data
In [131]:
quakes = data('quakes')
quakes.head()
quakes.tail()
Out[131]:
lat long depth mag stations
1 -20.42 181.62 562 4.8 41
2 -20.62 181.03 650 4.2 15
3 -26.00 184.10 42 5.4 43
4 -17.97 181.66 626 4.1 19
5 -20.42 181.96 649 4.0 11
Out[131]:
lat long depth mag stations
996 -25.93 179.54 470 4.4 22
997 -12.28 167.06 248 4.7 35
998 -20.13 184.20 244 4.5 34
999 -17.40 187.80 40 4.5 14
1000 -21.59 170.56 165 6.0 119

numpy, pandas imports

In [6]:
import numpy
In [133]:
help(numpy.loadtxt)
Help on function loadtxt in module numpy.lib.npyio:

loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
    Load data from a text file.
    
    Each row in the text file must have the same number of values.
    
    Parameters
    ----------
    fname : file, str, or pathlib.Path
        File, filename, or generator to read.  If the filename extension is
        ``.gz`` or ``.bz2``, the file is first decompressed. Note that
        generators should return byte strings for Python 3k.
    dtype : data-type, optional
        Data-type of the resulting array; default: float.  If this is a
        structured data-type, the resulting array will be 1-dimensional, and
        each row will be interpreted as an element of the array.  In this
        case, the number of columns used must match the number of fields in
        the data-type.
    comments : str or sequence, optional
        The characters or list of characters used to indicate the start of a
        comment;
        default: '#'.
    delimiter : str, optional
        The string used to separate values.  By default, this is any
        whitespace.
    converters : dict, optional
        A dictionary mapping column number to a function that will convert
        that column to a float.  E.g., if column 0 is a date string:
        ``converters = {0: datestr2num}``.  Converters can also be used to
        provide a default value for missing data (but see also `genfromtxt`):
        ``converters = {3: lambda s: float(s.strip() or 0)}``.  Default: None.
    skiprows : int, optional
        Skip the first `skiprows` lines; default: 0.
    
    usecols : int or sequence, optional
        Which columns to read, with 0 being the first. For example,
        usecols = (1,4,5) will extract the 2nd, 5th and 6th columns.
        The default, None, results in all columns being read.
    
        .. versionadded:: 1.11.0
    
        Also when a single column has to be read it is possible to use
        an integer instead of a tuple. E.g ``usecols = 3`` reads the
        fourth column the same way as `usecols = (3,)`` would.
    
    unpack : bool, optional
        If True, the returned array is transposed, so that arguments may be
        unpacked using ``x, y, z = loadtxt(...)``.  When used with a structured
        data-type, arrays are returned for each field.  Default is False.
    ndmin : int, optional
        The returned array will have at least `ndmin` dimensions.
        Otherwise mono-dimensional axes will be squeezed.
        Legal values: 0 (default), 1 or 2.
    
        .. versionadded:: 1.6.0
    
    Returns
    -------
    out : ndarray
        Data read from the text file.
    
    See Also
    --------
    load, fromstring, fromregex
    genfromtxt : Load data with missing values handled as specified.
    scipy.io.loadmat : reads MATLAB data files
    
    Notes
    -----
    This function aims to be a fast reader for simply formatted files.  The
    `genfromtxt` function provides more sophisticated handling of, e.g.,
    lines with missing values.
    
    .. versionadded:: 1.10.0
    
    The strings produced by the Python float.hex method can be used as
    input for floats.
    
    Examples
    --------
    >>> from io import StringIO   # StringIO behaves like a file object
    >>> c = StringIO("0 1\n2 3")
    >>> np.loadtxt(c)
    array([[ 0.,  1.],
           [ 2.,  3.]])
    
    >>> d = StringIO("M 21 72\nF 35 58")
    >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
    ...                      'formats': ('S1', 'i4', 'f4')})
    array([('M', 21, 72.0), ('F', 35, 58.0)],
          dtype=[('gender', '|S1'), ('age', '<i4'), ('weight', '<f4')])
    
    >>> c = StringIO("1,0,2\n3,0,4")
    >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
    >>> x
    array([ 1.,  3.])
    >>> y
    array([ 2.,  4.])

In [134]:
    array1=numpy.loadtxt(
        "compteurs.txt",
        delimiter='\t',
        usecols=range(4),
        dtype='str'
    )
    array1
Out[134]:
array([["b'20140908'", "b'49513'", "b'145'", "b'40'"],
       ["b'20141123'", "b'49674'", "b'152'", "b'50'"],
       ["b'20150403'", "b'50393'", "b'194'", "b'69'"],
       ["b'20150912'", "b'51089'", "b'230'", "b'118'"],
       ["b'20151215'", "b'51264'", "b'235 '", "b'122'"],
       ["b'20160130'", "b'51385'", "b'241'", "b'126'"],
       ["b'20160330'", "b'51551'", "b'249'", "b'131'"],
       ["b'20160415'", "b'51594'", "b'251'", "b'134'"],
       ["b'20160608'", "b'51823'", "b''", "b''"],
       ["b'20160625'", "b'51888'", "b'310'", "b'151'"],
       ["b'20160713'", "b''", "b''", "b'157'"],
       ["b'20160919'", "b'52357'", "b'331'", "b'186'"],
       ["b'20161208 '", "b'52433'", "b'332'", "b'187'"],
       ["b'20161212'", "b'52450'", "b''", "b''"],
       ["b'20170222 '", "b'52711'", "b'341'", "b'193'"],
       ["b'20170415'", "b'52758'", "b'343'", "b'195'"],
       ["b'20170607'", "b'53086'", "b''", "b''"],
       ["b'20170609'", "b''", "b'382'", "b''"],
       ["b'20170620'", "b'53086'", "b'384'", "b'217 '"]], 
      dtype='<U12')

The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.

In [135]:
help(numpy.genfromtxt)
Help on function genfromtxt in module numpy.lib.npyio:

genfromtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=None, replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None)
    Load data from a text file, with missing values handled as specified.
    
    Each line past the first `skip_header` lines is split at the `delimiter`
    character, and characters following the `comments` character are discarded.
    
    Parameters
    ----------
    fname : file, str, pathlib.Path, list of str, generator
        File, filename, list, or generator to read.  If the filename
        extension is `.gz` or `.bz2`, the file is first decompressed. Note
        that generators must return byte strings in Python 3k.  The strings
        in a list or produced by a generator are treated as lines.
    dtype : dtype, optional
        Data type of the resulting array.
        If None, the dtypes will be determined by the contents of each
        column, individually.
    comments : str, optional
        The character used to indicate the start of a comment.
        All the characters occurring on a line after a comment are discarded
    delimiter : str, int, or sequence, optional
        The string used to separate values.  By default, any consecutive
        whitespaces act as delimiter.  An integer or sequence of integers
        can also be provided as width(s) of each field.
    skiprows : int, optional
        `skiprows` was removed in numpy 1.10. Please use `skip_header` instead.
    skip_header : int, optional
        The number of lines to skip at the beginning of the file.
    skip_footer : int, optional
        The number of lines to skip at the end of the file.
    converters : variable, optional
        The set of functions that convert the data of a column to a value.
        The converters can also be used to provide a default value
        for missing data: ``converters = {3: lambda s: float(s or 0)}``.
    missing : variable, optional
        `missing` was removed in numpy 1.10. Please use `missing_values`
        instead.
    missing_values : variable, optional
        The set of strings corresponding to missing data.
    filling_values : variable, optional
        The set of values to be used as default when the data are missing.
    usecols : sequence, optional
        Which columns to read, with 0 being the first.  For example,
        ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns.
    names : {None, True, str, sequence}, optional
        If `names` is True, the field names are read from the first valid line
        after the first `skip_header` lines.
        If `names` is a sequence or a single-string of comma-separated names,
        the names will be used to define the field names in a structured dtype.
        If `names` is None, the names of the dtype fields will be used, if any.
    excludelist : sequence, optional
        A list of names to exclude. This list is appended to the default list
        ['return','file','print']. Excluded names are appended an underscore:
        for example, `file` would become `file_`.
    deletechars : str, optional
        A string combining invalid characters that must be deleted from the
        names.
    defaultfmt : str, optional
        A format used to define default field names, such as "f%i" or "f_%02i".
    autostrip : bool, optional
        Whether to automatically strip white spaces from the variables.
    replace_space : char, optional
        Character(s) used in replacement of white spaces in the variables
        names. By default, use a '_'.
    case_sensitive : {True, False, 'upper', 'lower'}, optional
        If True, field names are case sensitive.
        If False or 'upper', field names are converted to upper case.
        If 'lower', field names are converted to lower case.
    unpack : bool, optional
        If True, the returned array is transposed, so that arguments may be
        unpacked using ``x, y, z = loadtxt(...)``
    usemask : bool, optional
        If True, return a masked array.
        If False, return a regular array.
    loose : bool, optional
        If True, do not raise errors for invalid values.
    invalid_raise : bool, optional
        If True, an exception is raised if an inconsistency is detected in the
        number of columns.
        If False, a warning is emitted and the offending lines are skipped.
    max_rows : int,  optional
        The maximum number of rows to read. Must not be used with skip_footer
        at the same time.  If given, the value must be at least 1. Default is
        to read the entire file.
    
        .. versionadded:: 1.10.0
    
    Returns
    -------
    out : ndarray
        Data read from the text file. If `usemask` is True, this is a
        masked array.
    
    See Also
    --------
    numpy.loadtxt : equivalent function when no data is missing.
    
    Notes
    -----
    * When spaces are used as delimiters, or when no delimiter has been given
      as input, there should not be any missing data between two fields.
    * When the variables are named (either by a flexible dtype or with `names`,
      there must not be any header in the file (else a ValueError
      exception is raised).
    * Individual values are not stripped of spaces by default.
      When using a custom converter, make sure the function does remove spaces.
    
    References
    ----------
    .. [1] NumPy User Guide, section `I/O with NumPy
           <http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html>`_.
    
    Examples
    ---------
    >>> from io import StringIO
    >>> import numpy as np
    
    Comma delimited file with mixed dtype
    
    >>> s = StringIO("1,1.3,abcde")
    >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'),
    ... ('mystring','S5')], delimiter=",")
    >>> data
    array((1, 1.3, 'abcde'),
          dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])
    
    Using dtype = None
    
    >>> s.seek(0) # needed for StringIO example only
    >>> data = np.genfromtxt(s, dtype=None,
    ... names = ['myint','myfloat','mystring'], delimiter=",")
    >>> data
    array((1, 1.3, 'abcde'),
          dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])
    
    Specifying dtype and names
    
    >>> s.seek(0)
    >>> data = np.genfromtxt(s, dtype="i8,f8,S5",
    ... names=['myint','myfloat','mystring'], delimiter=",")
    >>> data
    array((1, 1.3, 'abcde'),
          dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])
    
    An example with fixed-width columns
    
    >>> s = StringIO("11.3abcde")
    >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],
    ...     delimiter=[1,3,5])
    >>> data
    array((1, 1.3, 'abcde'),
          dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', '|S5')])

In [136]:
array2=numpy.genfromtxt(
    "compteurs.txt", 
    dtype=[('date', '<S8'), ('HP', '<f8'), ('gaz', '<f8'), ('eau', '<f8')],
    #comments='#', 
    delimiter='\t', 
    #skip_header=0, skip_footer=0, 
    #converters={0:identity,1:identity,2:identity,3:identity}, 
    #missing_values=None, 
    #filling_values=None, 
    usecols=range(4), 
    names=True, 
    #excludelist=None, deletechars=None, replace_space='_', autostrip=False, 
    #case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, 
    #loose=True, invalid_raise=True, max_rows=None
)
array2
Out[136]:
array([(b'20140908',  49513.,  145.,   40.),
       (b'20141123',  49674.,  152.,   50.),
       (b'20150403',  50393.,  194.,   69.),
       (b'20150912',  51089.,  230.,  118.),
       (b'20151215',  51264.,  235.,  122.),
       (b'20160130',  51385.,  241.,  126.),
       (b'20160330',  51551.,  249.,  131.),
       (b'20160415',  51594.,  251.,  134.),
       (b'20160608',  51823.,   nan,   nan),
       (b'20160625',  51888.,  310.,  151.),
       (b'20160713',     nan,   nan,  157.),
       (b'20160919',  52357.,  331.,  186.),
       (b'20161208',  52433.,  332.,  187.),
       (b'20161212',  52450.,   nan,   nan),
       (b'20170222',  52711.,  341.,  193.),
       (b'20170415',  52758.,  343.,  195.),
       (b'20170607',  53086.,   nan,   nan),
       (b'20170609',     nan,  382.,   nan),
       (b'20170620',  53086.,  384.,  217.)], 
      dtype=[('date', 'S8'), ('HP', '<f8'), ('gaz', '<f8'), ('eau', '<f8')])
In [137]:
import pandas
pandas.read_table('compteurs.txt', sep='\t')
Out[137]:
# date HP gaz eau comment
0 20140908 49513.0 145.0 40.0 NaN
1 20141123 49674.0 152.0 50.0 NaN
2 20150403 50393.0 194.0 69.0 NaN
3 20150912 51089.0 230.0 118.0 NaN
4 20151215 51264.0 235.0 122.0 NaN
5 20160130 51385.0 241.0 126.0 NaN
6 20160330 51551.0 249.0 131.0 NaN
7 20160415 51594.0 251.0 134.0 NaN
8 20160608 51823.0 NaN NaN Enedis
9 20160625 51888.0 310.0 151.0 NaN
10 20160713 NaN NaN 157.0 NaN
11 20160919 52357.0 331.0 186.0 NaN
12 20161208 52433.0 332.0 187.0 NaN
13 20161212 52450.0 NaN NaN Enedis
14 20170222 52711.0 341.0 193.0 NaN
15 20170415 52758.0 343.0 195.0 contrat
16 20170607 53086.0 NaN NaN Enedis
17 20170609 NaN 382.0 NaN Engie
18 20170620 53086.0 384.0 217.0 Marcel

Operating system

Python can be used as a shell replacement, either by scripting or interactive use.

In [139]:
import os
In [140]:
dir(os)
Out[140]:
['CLD_CONTINUED',
 'CLD_DUMPED',
 'CLD_EXITED',
 'CLD_TRAPPED',
 'DirEntry',
 'EX_CANTCREAT',
 'EX_CONFIG',
 'EX_DATAERR',
 'EX_IOERR',
 'EX_NOHOST',
 'EX_NOINPUT',
 'EX_NOPERM',
 'EX_NOUSER',
 'EX_OK',
 'EX_OSERR',
 'EX_OSFILE',
 'EX_PROTOCOL',
 'EX_SOFTWARE',
 'EX_TEMPFAIL',
 'EX_UNAVAILABLE',
 'EX_USAGE',
 'F_LOCK',
 'F_OK',
 'F_TEST',
 'F_TLOCK',
 'F_ULOCK',
 'MutableMapping',
 'NGROUPS_MAX',
 'O_ACCMODE',
 'O_APPEND',
 'O_ASYNC',
 'O_CLOEXEC',
 'O_CREAT',
 'O_DIRECTORY',
 'O_DSYNC',
 'O_EXCL',
 'O_EXLOCK',
 'O_NDELAY',
 'O_NOCTTY',
 'O_NOFOLLOW',
 'O_NONBLOCK',
 'O_RDONLY',
 'O_RDWR',
 'O_SHLOCK',
 'O_SYNC',
 'O_TRUNC',
 'O_WRONLY',
 'PRIO_PGRP',
 'PRIO_PROCESS',
 'PRIO_USER',
 'P_ALL',
 'P_NOWAIT',
 'P_NOWAITO',
 'P_PGID',
 'P_PID',
 'P_WAIT',
 'PathLike',
 'RTLD_GLOBAL',
 'RTLD_LAZY',
 'RTLD_LOCAL',
 'RTLD_NODELETE',
 'RTLD_NOLOAD',
 'RTLD_NOW',
 'R_OK',
 'SCHED_FIFO',
 'SCHED_OTHER',
 'SCHED_RR',
 'SEEK_CUR',
 'SEEK_END',
 'SEEK_SET',
 'ST_NOSUID',
 'ST_RDONLY',
 'TMP_MAX',
 'WCONTINUED',
 'WCOREDUMP',
 'WEXITED',
 'WEXITSTATUS',
 'WIFCONTINUED',
 'WIFEXITED',
 'WIFSIGNALED',
 'WIFSTOPPED',
 'WNOHANG',
 'WNOWAIT',
 'WSTOPPED',
 'WSTOPSIG',
 'WTERMSIG',
 'WUNTRACED',
 'W_OK',
 'X_OK',
 '_Environ',
 '__all__',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_execvpe',
 '_exists',
 '_exit',
 '_fspath',
 '_get_exports_list',
 '_putenv',
 '_spawnvef',
 '_unsetenv',
 '_wrap_close',
 'abc',
 'abort',
 'access',
 'altsep',
 'chdir',
 'chflags',
 'chmod',
 'chown',
 'chroot',
 'close',
 'closerange',
 'confstr',
 'confstr_names',
 'cpu_count',
 'ctermid',
 'curdir',
 'defpath',
 'device_encoding',
 'devnull',
 'dup',
 'dup2',
 'environ',
 'environb',
 'errno',
 'error',
 'execl',
 'execle',
 'execlp',
 'execlpe',
 'execv',
 'execve',
 'execvp',
 'execvpe',
 'extsep',
 'fchdir',
 'fchmod',
 'fchown',
 'fdopen',
 'fork',
 'forkpty',
 'fpathconf',
 'fsdecode',
 'fsencode',
 'fspath',
 'fstat',
 'fstatvfs',
 'fsync',
 'ftruncate',
 'get_blocking',
 'get_exec_path',
 'get_inheritable',
 'get_terminal_size',
 'getcwd',
 'getcwdb',
 'getegid',
 'getenv',
 'getenvb',
 'geteuid',
 'getgid',
 'getgrouplist',
 'getgroups',
 'getloadavg',
 'getlogin',
 'getpgid',
 'getpgrp',
 'getpid',
 'getppid',
 'getpriority',
 'getsid',
 'getuid',
 'initgroups',
 'isatty',
 'kill',
 'killpg',
 'lchflags',
 'lchmod',
 'lchown',
 'linesep',
 'link',
 'listdir',
 'lockf',
 'lseek',
 'lstat',
 'major',
 'makedev',
 'makedirs',
 'minor',
 'mkdir',
 'mkfifo',
 'mknod',
 'name',
 'nice',
 'open',
 'openpty',
 'pardir',
 'path',
 'pathconf',
 'pathconf_names',
 'pathsep',
 'pipe',
 'popen',
 'pread',
 'putenv',
 'pwrite',
 'read',
 'readlink',
 'readv',
 'remove',
 'removedirs',
 'rename',
 'renames',
 'replace',
 'rmdir',
 'scandir',
 'sched_get_priority_max',
 'sched_get_priority_min',
 'sched_yield',
 'sendfile',
 'sep',
 'set_blocking',
 'set_inheritable',
 'setegid',
 'seteuid',
 'setgid',
 'setgroups',
 'setpgid',
 'setpgrp',
 'setpriority',
 'setregid',
 'setreuid',
 'setsid',
 'setuid',
 'spawnl',
 'spawnle',
 'spawnlp',
 'spawnlpe',
 'spawnv',
 'spawnve',
 'spawnvp',
 'spawnvpe',
 'st',
 'stat',
 'stat_float_times',
 'stat_result',
 'statvfs',
 'statvfs_result',
 'strerror',
 'supports_bytes_environ',
 'supports_dir_fd',
 'supports_effective_ids',
 'supports_fd',
 'supports_follow_symlinks',
 'symlink',
 'sync',
 'sys',
 'sysconf',
 'sysconf_names',
 'system',
 'tcgetpgrp',
 'tcsetpgrp',
 'terminal_size',
 'times',
 'times_result',
 'truncate',
 'ttyname',
 'umask',
 'uname',
 'uname_result',
 'unlink',
 'unsetenv',
 'urandom',
 'utime',
 'wait',
 'wait3',
 'wait4',
 'waitpid',
 'walk',
 'write',
 'writev']
In [141]:
os.getcwd()
os.getenv("PYTHONSTARTUP")
os.getenv("HOME")
Out[141]:
'/Users/alba/Documents/technique/python'
Out[141]:
'/Users/alba/.pythonrc'
Out[141]:
'/Users/alba'
In [143]:
os.stat("./whatsinpythonbelly.ipynb")
Out[143]:
os.stat_result(st_mode=33188, st_ino=88842658, st_dev=16777218, st_nlink=1, st_uid=501, st_gid=20, st_size=249295, st_atime=1500061687, st_mtime=1500061688, st_ctime=1500061688)

Kill kernel

In [ ]:
import os
os._exit(00)
In [144]:
import sys
In [145]:
sys.path
Out[145]:
['',
 '/Users/alba/Library/python',
 '/Users/alba/Documents/technique/python',
 '/Users/alba/anaconda3/lib/python36.zip',
 '/Users/alba/anaconda3/lib/python3.6',
 '/Users/alba/anaconda3/lib/python3.6/lib-dynload',
 '/Users/alba/anaconda3/lib/python3.6/site-packages',
 '/Users/alba/anaconda3/lib/python3.6/site-packages/Sphinx-1.5.6-py3.6.egg',
 '/Users/alba/anaconda3/lib/python3.6/site-packages/aeosa',
 '/Users/alba/anaconda3/lib/python3.6/site-packages/setuptools-27.2.0-py3.6.egg',
 '/Users/alba/anaconda3/lib/python3.6/site-packages/IPython/extensions',
 '/Users/alba/.ipython']
In [146]:
stream1=open('die.py')
i=0
while i<3:
    i+=1
    stream1.readline()
del stream1,i
Out[146]:
'#!/usr/bin/env python\n'
Out[146]:
'"""Define a Die and simulate rolling it a dozen times."""\n'
Out[146]:
'import random\n'

Simulating an open text file: inline openfile.

In [ ]:
import io
stream1=io.StringIO("20170607	53086			Enedis")
In [ ]:
stream1.readline()

Connected device

Raspberry Pi

A blinking LED, that can be turned on and off by pushing a button (not a switch).

In [147]:
!cat "LED+pb.py"
#!/usr/bin/env python3
from RPi.GPIO import *
import time
setmode(BCM) # pin number relative to BCM chip
setup(4,OUT) # where LED

setup(17,IN,pull_up_down=PUD_UP) # push button, default 1

pressed=False

print("Push button to start.")
while True:
    time.sleep(.01)
    if input(17)==0:
        pressed=not(pressed)
        time.sleep(.5) # max push time
    elif pressed:
        output(4,1)
        time.sleep(.05)
        output(4,0)
        time.sleep(.5)
    else:
        continue

In order to turn off the flashing LED, on must be lucky enough to push at the right moment yet not too long, or else it will be considered as pushing twice. This can be improved with asynchronous programming, see module asyncio.

Scientific operations

Symbolic computing with sympy

In [148]:
import sympy

dir(sympy)
Out[148]:
['Abs',
 'AccumBounds',
 'Add',
 'Adjoint',
 'AlgebraicField',
 'AlgebraicNumber',
 'And',
 'AppliedPredicate',
 'AssumptionsContext',
 'Atom',
 'AtomicExpr',
 'BasePolynomialError',
 'Basic',
 'BlockDiagMatrix',
 'BlockMatrix',
 'C',
 'CC',
 'CRootOf',
 'Catalan',
 'Chi',
 'Ci',
 'Circle',
 'ClassRegistry',
 'CoercionFailed',
 'Complement',
 'ComplexField',
 'ComplexRegion',
 'ComplexRootOf',
 'ComputationFailed',
 'ConditionSet',
 'Contains',
 'CosineTransform',
 'Curve',
 'DeferredVector',
 'Derivative',
 'Determinant',
 'DiagonalMatrix',
 'DiagonalOf',
 'Dict',
 'DiracDelta',
 'Domain',
 'DomainError',
 'Dummy',
 'E',
 'E1',
 'EPath',
 'EX',
 'Ei',
 'Eijk',
 'Ellipse',
 'EmptySequence',
 'EmptySet',
 'Eq',
 'Equality',
 'Equivalent',
 'EulerGamma',
 'EvaluationFailed',
 'ExactQuotientFailed',
 'Expr',
 'ExpressionDomain',
 'ExtraneousFactors',
 'FF',
 'FF_gmpy',
 'FF_python',
 'FU',
 'FallingFactorial',
 'FiniteField',
 'FiniteSet',
 'FlagError',
 'Float',
 'FourierTransform',
 'FractionField',
 'Function',
 'FunctionClass',
 'FunctionMatrix',
 'GF',
 'GMPYFiniteField',
 'GMPYIntegerRing',
 'GMPYRationalField',
 'Ge',
 'GeneratorsError',
 'GeneratorsNeeded',
 'GeometryError',
 'GoldenRatio',
 'GramSchmidt',
 'GreaterThan',
 'GroebnerBasis',
 'Gt',
 'HadamardProduct',
 'HankelTransform',
 'Heaviside',
 'HeuristicGCDFailed',
 'HomomorphismFailed',
 'I',
 'ITE',
 'Id',
 'Identity',
 'Idx',
 'ImageSet',
 'ImmutableDenseMatrix',
 'ImmutableMatrix',
 'ImmutableSparseMatrix',
 'Implies',
 'Indexed',
 'IndexedBase',
 'Integer',
 'IntegerRing',
 'Integral',
 'Intersection',
 'Interval',
 'Inverse',
 'InverseCosineTransform',
 'InverseFourierTransform',
 'InverseHankelTransform',
 'InverseLaplaceTransform',
 'InverseMellinTransform',
 'InverseSineTransform',
 'IsomorphismFailed',
 'KroneckerDelta',
 'LC',
 'LM',
 'LT',
 'Lambda',
 'LambertW',
 'LaplaceTransform',
 'Le',
 'LessThan',
 'LeviCivita',
 'Li',
 'Limit',
 'Line',
 'Line3D',
 'Lt',
 'MatAdd',
 'MatMul',
 'MatPow',
 'Matrix',
 'MatrixBase',
 'MatrixExpr',
 'MatrixSlice',
 'MatrixSymbol',
 'Max',
 'MellinTransform',
 'Min',
 'Mod',
 'Monomial',
 'Mul',
 'MultivariatePolynomialError',
 'MutableDenseMatrix',
 'MutableMatrix',
 'MutableSparseMatrix',
 'N',
 'Nand',
 'Ne',
 'NonSquareMatrixError',
 'Nor',
 'Not',
 'NotAlgebraic',
 'NotInvertible',
 'NotReversible',
 'Number',
 'NumberSymbol',
 'O',
 'OperationNotSupported',
 'OptionError',
 'Options',
 'Or',
 'Order',
 'POSform',
 'Piecewise',
 'Plane',
 'Point',
 'Point2D',
 'Point3D',
 'PoleError',
 'PolificationFailed',
 'Poly',
 'Polygon',
 'PolynomialDivisionFailed',
 'PolynomialError',
 'PolynomialRing',
 'Pow',
 'PrecisionExhausted',
 'Predicate',
 'Product',
 'ProductSet',
 'PurePoly',
 'PythonFiniteField',
 'PythonIntegerRing',
 'PythonRationalField',
 'Q',
 'QQ',
 'QQ_gmpy',
 'QQ_python',
 'RR',
 'Range',
 'Rational',
 'RationalField',
 'Ray',
 'Ray3D',
 'RealField',
 'RealNumber',
 'RefinementFailed',
 'RegularPolygon',
 'Rel',
 'RisingFactorial',
 'RootOf',
 'RootSum',
 'S',
 'SOPform',
 'SYMPY_DEBUG',
 'Segment',
 'Segment3D',
 'SeqAdd',
 'SeqFormula',
 'SeqMul',
 'SeqPer',
 'Set',
 'ShapeError',
 'Shi',
 'Si',
 'Sieve',
 'SineTransform',
 'SparseMatrix',
 'StrictGreaterThan',
 'StrictLessThan',
 'Subs',
 'Sum',
 'Symbol',
 'SymmetricDifference',
 'SympifyError',
 'TableForm',
 'Trace',
 'Transpose',
 'Triangle',
 'Tuple',
 'Unequality',
 'UnificationFailed',
 'Union',
 'UnivariatePolynomialError',
 'Wild',
 'WildFunction',
 'Xor',
 'Ynm',
 'Ynm_c',
 'ZZ',
 'ZZ_gmpy',
 'ZZ_python',
 'ZeroMatrix',
 'Znm',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__path__',
 '__spec__',
 '__sympy_debug',
 '__version__',
 'acos',
 'acosh',
 'acot',
 'acoth',
 'acsc',
 'add',
 'adjoint',
 'airyai',
 'airyaiprime',
 'airybi',
 'airybiprime',
 'apart',
 'apart_list',
 'apply_finite_diff',
 'are_similar',
 'arg',
 'as_finite_diff',
 'asec',
 'asech',
 'asin',
 'asinh',
 'ask',
 'ask_generated',
 'assemble_partfrac_list',
 'assoc_laguerre',
 'assoc_legendre',
 'assume',
 'assuming',
 'assumptions',
 'atan',
 'atan2',
 'atanh',
 'basic',
 'bell',
 'bernoulli',
 'besseli',
 'besselj',
 'besselk',
 'besselsimp',
 'bessely',
 'beta',
 'binomial',
 'binomial_coefficients',
 'binomial_coefficients_list',
 'bivariate',
 'block_collapse',
 'blockcut',
 'bool_map',
 'boolalg',
 'bottom_up',
 'bspline_basis',
 'bspline_basis_set',
 'cache',
 'cacheit',
 'calculus',
 'cancel',
 'capture',
 'cartes',
 'casoratian',
 'catalan',
 'cbrt',
 'ccode',
 'ceiling',
 'centroid',
 'chebyshevt',
 'chebyshevt_poly',
 'chebyshevt_root',
 'chebyshevu',
 'chebyshevu_poly',
 'chebyshevu_root',
 'checkodesol',
 'checkpdesol',
 'checksol',
 'class_registry',
 'classify_ode',
 'classify_pde',
 'closest_points',
 'cofactors',
 'collect',
 'collect_const',
 'combinatorial',
 'combsimp',
 'comp',
 'compatibility',
 'compose',
 'concrete',
 'conditionset',
 'conjugate',
 'construct_domain',
 'containers',
 'contains',
 'content',
 'continued_fraction',
 'continued_fraction_convergents',
 'continued_fraction_iterator',
 'continued_fraction_periodic',
 'continued_fraction_reduce',
 'convex_hull',
 'core',
 'coreerrors',
 'cos',
 'cosh',
 'cosine_transform',
 'cot',
 'coth',
 'count_ops',
 'count_roots',
 'csc',
 'csch',
 'cse',
 'cse_main',
 'cse_opts',
 'curve',
 'cycle_length',
 'cyclotomic_poly',
 'decompogen',
 'decompose',
 'decorator',
 'decorators',
 'default_sort_key',
 'deg',
 'degree',
 'degree_list',
 'denom',
 'dense',
 'deprecated',
 'det',
 'det_quick',
 'deutils',
 'diag',
 'dict_merge',
 'diff',
 'difference_delta',
 'digamma',
 'dirichlet_eta',
 'discriminant',
 'div',
 'divisor_count',
 'divisor_sigma',
 'divisors',
 'doctest',
 'dsolve',
 'egyptian_fraction',
 'elementary',
 'ellipse',
 'elliptic_e',
 'elliptic_f',
 'elliptic_k',
 'elliptic_pi',
 'entity',
 'enumerative',
 'epath',
 'epathtools',
 'erf',
 'erf2',
 'erf2inv',
 'erfc',
 'erfcinv',
 'erfi',
 'erfinv',
 'euler',
 'euler_equations',
 'evalf',
 'evaluate',
 'exceptions',
 'exp',
 'exp_polar',
 'expand',
 'expand_complex',
 'expand_func',
 'expand_log',
 'expand_mul',
 'expand_multinomial',
 'expand_power_base',
 'expand_power_exp',
 'expand_trig',
 'expint',
 'expr',
 'expr_with_intlimits',
 'expr_with_limits',
 'expressions',
 'exprtools',
 'exptrigsimp',
 'exquo',
 'external',
 'eye',
 'factor',
 'factor_',
 'factor_list',
 'factor_nc',
 'factor_terms',
 'factorial',
 'factorial2',
 'factorint',
 'factorrat',
 'facts',
 'false',
 'fancysets',
 'farthest_points',
 'fcode',
 'ff',
 'fibonacci',
 'field',
 'field_isomorphism',
 'filldedent',
 'finite_diff',
 'finite_diff_weights',
 'flatten',
 'floor',
 'fourier_series',
 'fourier_transform',
 'fps',
 'frac',
 'fraction',
 'fresnelc',
 'fresnels',
 'fu',
 'function',
 'functions',
 'gamma',
 'gcd',
 'gcd_list',
 'gcd_terms',
 'gcdex',
 'gegenbauer',
 'generate',
 'genocchi',
 'geometry',
 'get_contraction_structure',
 'get_indices',
 'gff',
 'gff_list',
 'gosper',
 'grevlex',
 'grlex',
 'groebner',
 'ground_roots',
 'group',
 'gruntz',
 'hadamard_product',
 'half_gcdex',
 'hankel1',
 'hankel2',
 'hankel_transform',
 'harmonic',
 'has_dups',
 'has_variety',
 'hermite',
 'hermite_poly',
 'hessian',
 'hn1',
 'hn2',
 'homogeneous_order',
 'horner',
 'hyper',
 'hyperexpand',
 'hypersimilar',
 'hypersimp',
 'idiff',
 'igcd',
 'igrevlex',
 'igrlex',
 'ilcm',
 'ilex',
 'im',
 'imageset',
 'immutable',
 'index_methods',
 'indexed',
 'inequalities',
 'inference',
 'init_printing',
 'init_session',
 'integer_nthroot',
 'integrals',
 'integrate',
 'interactive',
 'interactive_traversal',
 'interpolate',
 'interpolating_poly',
 'intersection',
 'intervals',
 'inv_quick',
 'inverse_cosine_transform',
 'inverse_fourier_transform',
 'inverse_hankel_transform',
 'inverse_laplace_transform',
 'inverse_mellin_transform',
 'inverse_sine_transform',
 'invert',
 'is_decreasing',
 'is_increasing',
 'is_monotonic',
 'is_nthpow_residue',
 'is_primitive_root',
 'is_quad_residue',
 'is_strictly_decreasing',
 'is_strictly_increasing',
 'is_zero_dimensional',
 'isolate',
 'isprime',
 'iterables',
 'itermonomials',
 'jacobi',
 'jacobi_normalized',
 'jacobi_poly',
 'jacobi_symbol',
 'jn',
 'jn_zeros',
 'jordan_cell',
 'jscode',
 'julia_code',
 'laguerre',
 'laguerre_poly',
 'lambdify',
 'laplace_transform',
 'latex',
 'lcm',
 'lcm_list',
 'legendre',
 'legendre_poly',
 'legendre_symbol',
 'lerchphi',
 'lex',
 'li',
 'limit',
 'limit_seq',
 'line',
 'line3d',
 'line_integrate',
 'linear_eq_to_matrix',
 'linsolve',
 'list2numpy',
 'ln',
 'log',
 'logcombine',
 'loggamma',
 'logic',
 'lowergamma',
 'lucas',
 'magic',
 'manualintegrate',
 'mathematica_code',
 'mathieuc',
 'mathieucprime',
 'mathieus',
 'mathieusprime',
 'matrices',
 'matrix2numpy',
 'matrix_multiply_elementwise',
 'matrix_symbols',
 'meijerg',
 'meijerint',
 'mellin_transform',
 'memoization',
 'memoize_property',
 'minimal_polynomial',
 'minpoly',
 'misc',
 'mobius',
 'mod',
 'mod_inverse',
 'monic',
 'mpmath',
 'mul',
 'multidimensional',
 'multinomial',
 'multinomial_coefficients',
 'multiplicity',
 'n_order',
 'nan',
 'nextprime',
 'nfloat',
 'not_empty_in',
 'npartitions',
 'nroots',
 'nsimplify',
 'nsolve',
 'nth_power_roots_poly',
 'ntheory',
 'nthroot_mod',
 'numbered_symbols',
 'numbers',
 'numer',
 'octave_code',
 'ode',
 'ode_order',
 'ones',
 'oo',
 'operations',
 'ordered',
 'pager_print',
 'parallel_poly_from_expr',
 'parsing',
 'partitions_',
 'pde',
 'pde_separate',
 'pde_separate_add',
 'pde_separate_mul',
 'pdiv',
 'pdsolve',
 'perfect_power',
 'periodic_argument',
 'pexquo',
 'pi',
 'piecewise_fold',
 'plane',
 'plot',
 'plot_backends',
 'plot_implicit',
 'plotting',
 'point',
 'polar_lift',
 'polarify',
 'pollard_pm1',
 'pollard_rho',
 'poly',
 'poly_from_expr',
 'polygamma',
 'polygon',
 'polylog',
 'polys',
 'polysys',
 'posify',
 'postfixes',
 'postorder_traversal',
 'powdenest',
 'power',
 'powsimp',
 'pprint',
 'pprint_try_use_unicode',
 'pprint_use_unicode',
 'pquo',
 'prefixes',
 'prem',
 'preorder_traversal',
 'pretty',
 'pretty_print',
 'preview',
 'prevprime',
 'prime',
 'primefactors',
 'primepi',
 'primerange',
 'primetest',
 'primitive',
 'primitive_element',
 'primitive_root',
 'primorial',
 'principal_branch',
 'print_gtk',
 'print_python',
 'print_tree',
 'printing',
 'prod',
 'product',
 'products',
 'public',
 'python',
 'quadratic_residues',
 'quo',
 'rad',
 'radsimp',
 'randMatrix',
 'random_poly',
 'randprime',
 'rational_interpolate',
 'ratsimp',
 'ratsimpmodprime',
 'rcollect',
 're',
 'real_root',
 'real_roots',
 'recurr',
 'reduce_abs_inequalities',
 'reduce_abs_inequality',
 'reduce_inequalities',
 'reduced',
 'refine',
 'refine_root',
 'register_handler',
 'relational',
 'release',
 'rem',
 'remove_handler',
 'reshape',
 'residue',
 'residue_ntheory',
 'resultant',
 'rf',
 'ring',
 'root',
 'rootof',
 'roots',
 'rot_axis1',
 'rot_axis2',
 'rot_axis3',
 'rsolve',
 'rsolve_hyper',
 'rsolve_poly',
 'rsolve_ratio',
 'rules',
 'runtests',
 'satisfiable',
 'sec',
 'sech',
 'separatevars',
 'sequence',
 'series',
 'seterr',
 'sets',
 'sfield',
 'sieve',
 'sift',
 'sign',
 'signsimp',
 'simplify',
 'simplify_logic',
 'sin',
 'sinc',
 'sine_transform',
 'singleton',
 'singularities',
 'sinh',
 'solve',
 'solve_linear',
 'solve_linear_system',
 'solve_linear_system_LU',
 'solve_poly_inequality',
 'solve_poly_system',
 'solve_rational_inequalities',
 'solve_triangulated',
 'solve_undetermined_coeffs',
 'solve_univariate_inequality',
 'solvers',
 'solveset',
 'source',
 'sparse',
 'special',
 'sqf',
 'sqf_list',
 'sqf_norm',
 'sqf_part',
 'sqrt',
 'sqrt_mod',
 'sqrt_mod_iter',
 'sqrtdenest',
 'srepr',
 'sring',
 'sstr',
 'sstrrepr',
 'stieltjes',
 'strategies',
 'sturm',
 'subfactorial',
 'subresultants',
 'subsets',
 'summation',
 'summations',
 'swinnerton_dyer_poly',
 'symarray',
 'symbol',
 'symbols',
 'symmetric_poly',
 'symmetrize',
 'sympify',
 'take',
 'tan',
 'tanh',
 'tensor',
 'terms_gcd',
 'test',
 'textplot',
 'threaded',
 'timed',
 'timeutils',
 'to_cnf',
 'to_dnf',
 'to_nnf',
 'to_number_field',
 'together',
 'topological_sort',
 'totient',
 'trace',
 'trailing',
 'transforms',
 'transpose',
 'traversaltools',
 'trigamma',
 'trigonometry',
 'trigsimp',
 'true',
 'trunc',
 'unbranched_argument',
 'unflatten',
 'unpolarify',
 'uppergamma',
 'use',
 'util',
 'utilities',
 'var',
 'variations',
 'vectorize',
 'vfield',
 'viete',
 'vring',
 'wronskian',
 'xfield',
 'xring',
 'xthreaded',
 'yn',
 'zeros',
 'zeta',
 'zoo']
In [149]:
x,y,z,t=sympy.symbols('x y z t')

expr=(x+y)**3

expr

expr1=expr.expand()

expr1

expr1.factor()

del x,y,z,t,expr,expr1
Out[149]:
(x + y)**3
Out[149]:
x**3 + 3*x**2*y + 3*x*y**2 + y**3
Out[149]:
(x + y)**3

Dot (inner) product: it is much easier to see what is going on with a function that does not evaluate.

In [150]:
f=sympy.symbols('f')

sum(map(f,zip([1,4,2],[5,6,2])))

sum(map((lambda x:f(x[0],x[1])),zip([1,4,2],[5,6,2])))

[[f(x,y) for y in [1,2,3]] for x in [3,1,4]]

del f
Out[150]:
f((1, 5)) + f((2, 2)) + f((4, 6))
Out[150]:
f(1, 5) + f(2, 2) + f(4, 6)
Out[150]:
[[f(3, 1), f(3, 2), f(3, 3)],
 [f(1, 1), f(1, 2), f(1, 3)],
 [f(4, 1), f(4, 2), f(4, 3)]]

Working on homogeneous arrays with numpy

In [151]:
import numpy
numpy.version.version
Out[151]:
'1.12.1'
In [152]:
numpy.array([(1.5,2,3), (4,5,6)])

numpy.array([[1.5,2,3], [4,5,6]])

x=numpy.ones( (2,3,4) )
Out[152]:
array([[ 1.5,  2. ,  3. ],
       [ 4. ,  5. ,  6. ]])
Out[152]:
array([[ 1.5,  2. ,  3. ],
       [ 4. ,  5. ,  6. ]])

range does not work with decimal step.

In [153]:
numpy.arange(0,10,.1)

numpy.linspace(0,10,101)

numpy.linspace(0,10,24).reshape(2,3,4) 
Out[153]:
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ,
        1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9,  2. ,  2.1,
        2.2,  2.3,  2.4,  2.5,  2.6,  2.7,  2.8,  2.9,  3. ,  3.1,  3.2,
        3.3,  3.4,  3.5,  3.6,  3.7,  3.8,  3.9,  4. ,  4.1,  4.2,  4.3,
        4.4,  4.5,  4.6,  4.7,  4.8,  4.9,  5. ,  5.1,  5.2,  5.3,  5.4,
        5.5,  5.6,  5.7,  5.8,  5.9,  6. ,  6.1,  6.2,  6.3,  6.4,  6.5,
        6.6,  6.7,  6.8,  6.9,  7. ,  7.1,  7.2,  7.3,  7.4,  7.5,  7.6,
        7.7,  7.8,  7.9,  8. ,  8.1,  8.2,  8.3,  8.4,  8.5,  8.6,  8.7,
        8.8,  8.9,  9. ,  9.1,  9.2,  9.3,  9.4,  9.5,  9.6,  9.7,  9.8,
        9.9])
Out[153]:
array([  0. ,   0.1,   0.2,   0.3,   0.4,   0.5,   0.6,   0.7,   0.8,
         0.9,   1. ,   1.1,   1.2,   1.3,   1.4,   1.5,   1.6,   1.7,
         1.8,   1.9,   2. ,   2.1,   2.2,   2.3,   2.4,   2.5,   2.6,
         2.7,   2.8,   2.9,   3. ,   3.1,   3.2,   3.3,   3.4,   3.5,
         3.6,   3.7,   3.8,   3.9,   4. ,   4.1,   4.2,   4.3,   4.4,
         4.5,   4.6,   4.7,   4.8,   4.9,   5. ,   5.1,   5.2,   5.3,
         5.4,   5.5,   5.6,   5.7,   5.8,   5.9,   6. ,   6.1,   6.2,
         6.3,   6.4,   6.5,   6.6,   6.7,   6.8,   6.9,   7. ,   7.1,
         7.2,   7.3,   7.4,   7.5,   7.6,   7.7,   7.8,   7.9,   8. ,
         8.1,   8.2,   8.3,   8.4,   8.5,   8.6,   8.7,   8.8,   8.9,
         9. ,   9.1,   9.2,   9.3,   9.4,   9.5,   9.6,   9.7,   9.8,
         9.9,  10. ])
Out[153]:
array([[[  0.        ,   0.43478261,   0.86956522,   1.30434783],
        [  1.73913043,   2.17391304,   2.60869565,   3.04347826],
        [  3.47826087,   3.91304348,   4.34782609,   4.7826087 ]],

       [[  5.2173913 ,   5.65217391,   6.08695652,   6.52173913],
        [  6.95652174,   7.39130435,   7.82608696,   8.26086957],
        [  8.69565217,   9.13043478,   9.56521739,  10.        ]]])
In [154]:
numpy.sin(1)
Out[154]:
0.8414709848078965
In [155]:
numpy.sin(x)
Out[155]:
array([[[ 0.84147098,  0.84147098,  0.84147098,  0.84147098],
        [ 0.84147098,  0.84147098,  0.84147098,  0.84147098],
        [ 0.84147098,  0.84147098,  0.84147098,  0.84147098]],

       [[ 0.84147098,  0.84147098,  0.84147098,  0.84147098],
        [ 0.84147098,  0.84147098,  0.84147098,  0.84147098],
        [ 0.84147098,  0.84147098,  0.84147098,  0.84147098]]])
In [156]:
numpy.array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]]).sum(axis=0)
Out[156]:
array([12, 15, 18, 21])
In [157]:
numpy.array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]]).sum(axis=1)
Out[157]:
array([ 6, 22, 38])
In [158]:
numpy.array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]])[0:5,1:3]
Out[158]:
array([[ 1,  2],
       [11, 12],
       [21, 22],
       [31, 32],
       [41, 42]])
In [159]:
numpy.array([[ 1,  2],
       [11, 12],
       [21, 22],
       [31, 32],
       [41, 42]]).transpose()

numpy.array([[ 1,  2],
       [11, 12],
       [21, 22],
       [31, 32],
       [41, 42]]).ravel()
Out[159]:
array([[ 1, 11, 21, 31, 41],
       [ 2, 12, 22, 32, 42]])
Out[159]:
array([ 1,  2, 11, 12, 21, 22, 31, 32, 41, 42])
In [160]:
numpy.apply_along_axis(
    sum,
    0,
    numpy.array([
        [ 1,  2],
        [11, 12],
        [21, 22],
        [31, 32],
        [41, 42]])
                   )

numpy.apply_along_axis(
    sum,
    1,
    numpy.array([
        [ 1,  2],
        [11, 12],
        [21, 22],
        [31, 32],
        [41, 42]])
                   )
Out[160]:
array([105, 110])
Out[160]:
array([ 3, 23, 43, 63, 83])
In [161]:
numpy.vectorize(int)([['1','2','3','4','5'],['7','2','3','4','5']])
Out[161]:
array([[1, 2, 3, 4, 5],
       [7, 2, 3, 4, 5]])

Import and visualize time table.

In [162]:
!cat compteurs-1.txt
#  date		P	C	eau

20140823	32995	9570	66
20140901	33018	9609	67
20141006	33107	9783	77.5
20141101	33196	9989	89
20141130	33301	10252	100.5
20150101	33459	10612	112
20150110	33522	10726		selon facture
20150131 	33613	11012	125.7
20150301	33772	11432	139
20150330	33837	11679	146.5
20150430	33916 	11946	157
20150529	34003	12177	168
20150823	34205	12441	185
20150901	34222	12465	187
20151010	34297	12613	191
20151031	34354	12732	194.5
20151204	34470	12949	200
20160103	34551	13096	203
20160121	34621	13201		selon facture
20160126	34661		207
20160129		13253	
20160209	34731	13334	209
20160301	34801	13452	212
20160405	34921	13677	217
20160502	34983	13804	220
20160605 	35067	13977	226
20161025	35451 	14566	252
20161101	35465	14580	252
20161121			255
20170203			286	Noémie
20170502			325
20170702			352	Stefan

As there are empty records, dtype cannot be float but can be bytes or str.

In [163]:
fname="compteurs-1.txt"
ncols=4

def identity(x):return x

array1=numpy.loadtxt(
    fname,
    delimiter='\t',
    usecols=range(ncols),
    converters={0:identity,1:identity,2:identity,3:identity},
    dtype='str'
)
array1
Out[163]:
array([['20140823', '32995', '9570', '66'],
       ['20140901', '33018', '9609', '67'],
       ['20141006', '33107', '9783', '77.5'],
       ['20141101', '33196', '9989', '89'],
       ['20141130', '33301', '10252', '100.5'],
       ['20150101', '33459', '10612', '112'],
       ['20150110', '33522', '10726', ''],
       ['20150131 ', '33613', '11012', '125.7'],
       ['20150301', '33772', '11432', '139'],
       ['20150330', '33837', '11679', '146.5'],
       ['20150430', '33916 ', '11946', '157'],
       ['20150529', '34003', '12177', '168'],
       ['20150823', '34205', '12441', '185'],
       ['20150901', '34222', '12465', '187'],
       ['20151010', '34297', '12613', '191'],
       ['20151031', '34354', '12732', '194.5'],
       ['20151204', '34470', '12949', '200'],
       ['20160103', '34551', '13096', '203'],
       ['20160121', '34621', '13201', ''],
       ['20160126', '34661', '', '207'],
       ['20160129', '', '13253', ''],
       ['20160209', '34731', '13334', '209'],
       ['20160301', '34801', '13452', '212'],
       ['20160405', '34921', '13677', '217'],
       ['20160502', '34983', '13804', '220'],
       ['20160605 ', '35067', '13977', '226'],
       ['20161025', '35451 ', '14566', '252'],
       ['20161101', '35465', '14580', '252'],
       ['20161121', '', '', '255'],
       ['20170203', '', '', '286'],
       ['20170502', '', '', '325'],
       ['20170702', '', '', '352']], 
      dtype='<U9')
In [164]:
import matplotlib.dates
refdatestr='20100101'
refdate=matplotlib.dates.datestr2num(refdatestr)

dates1=numpy.vectorize(lambda x:matplotlib.dates.datestr2num(x)-refdate)(
    array1[:,0]
)
dates1
Out[164]:
array([ 1695.,  1704.,  1739.,  1765.,  1794.,  1826.,  1835.,  1856.,
        1885.,  1914.,  1945.,  1974.,  2060.,  2069.,  2108.,  2129.,
        2163.,  2193.,  2211.,  2216.,  2219.,  2230.,  2251.,  2286.,
        2313.,  2347.,  2489.,  2496.,  2516.,  2590.,  2678.,  2739.])
In [165]:
array1
Out[165]:
array([['20140823', '32995', '9570', '66'],
       ['20140901', '33018', '9609', '67'],
       ['20141006', '33107', '9783', '77.5'],
       ['20141101', '33196', '9989', '89'],
       ['20141130', '33301', '10252', '100.5'],
       ['20150101', '33459', '10612', '112'],
       ['20150110', '33522', '10726', ''],
       ['20150131 ', '33613', '11012', '125.7'],
       ['20150301', '33772', '11432', '139'],
       ['20150330', '33837', '11679', '146.5'],
       ['20150430', '33916 ', '11946', '157'],
       ['20150529', '34003', '12177', '168'],
       ['20150823', '34205', '12441', '185'],
       ['20150901', '34222', '12465', '187'],
       ['20151010', '34297', '12613', '191'],
       ['20151031', '34354', '12732', '194.5'],
       ['20151204', '34470', '12949', '200'],
       ['20160103', '34551', '13096', '203'],
       ['20160121', '34621', '13201', ''],
       ['20160126', '34661', '', '207'],
       ['20160129', '', '13253', ''],
       ['20160209', '34731', '13334', '209'],
       ['20160301', '34801', '13452', '212'],
       ['20160405', '34921', '13677', '217'],
       ['20160502', '34983', '13804', '220'],
       ['20160605 ', '35067', '13977', '226'],
       ['20161025', '35451 ', '14566', '252'],
       ['20161101', '35465', '14580', '252'],
       ['20161121', '', '', '255'],
       ['20170203', '', '', '286'],
       ['20170502', '', '', '325'],
       ['20170702', '', '', '352']], 
      dtype='<U9')
In [166]:
[list(zip(*((record[0],float(record[1])) 
    for record in 
     list(filter(lambda x:x[-1]!='',zip(dates1,array1[:,column])))
       )))
     for column in range(1,ncols)
]
Out[166]:
[[(1695.0,
   1704.0,
   1739.0,
   1765.0,
   1794.0,
   1826.0,
   1835.0,
   1856.0,
   1885.0,
   1914.0,
   1945.0,
   1974.0,
   2060.0,
   2069.0,
   2108.0,
   2129.0,
   2163.0,
   2193.0,
   2211.0,
   2216.0,
   2230.0,
   2251.0,
   2286.0,
   2313.0,
   2347.0,
   2489.0,
   2496.0),
  (32995.0,
   33018.0,
   33107.0,
   33196.0,
   33301.0,
   33459.0,
   33522.0,
   33613.0,
   33772.0,
   33837.0,
   33916.0,
   34003.0,
   34205.0,
   34222.0,
   34297.0,
   34354.0,
   34470.0,
   34551.0,
   34621.0,
   34661.0,
   34731.0,
   34801.0,
   34921.0,
   34983.0,
   35067.0,
   35451.0,
   35465.0)],
 [(1695.0,
   1704.0,
   1739.0,
   1765.0,
   1794.0,
   1826.0,
   1835.0,
   1856.0,
   1885.0,
   1914.0,
   1945.0,
   1974.0,
   2060.0,
   2069.0,
   2108.0,
   2129.0,
   2163.0,
   2193.0,
   2211.0,
   2219.0,
   2230.0,
   2251.0,
   2286.0,
   2313.0,
   2347.0,
   2489.0,
   2496.0),
  (9570.0,
   9609.0,
   9783.0,
   9989.0,
   10252.0,
   10612.0,
   10726.0,
   11012.0,
   11432.0,
   11679.0,
   11946.0,
   12177.0,
   12441.0,
   12465.0,
   12613.0,
   12732.0,
   12949.0,
   13096.0,
   13201.0,
   13253.0,
   13334.0,
   13452.0,
   13677.0,
   13804.0,
   13977.0,
   14566.0,
   14580.0)],
 [(1695.0,
   1704.0,
   1739.0,
   1765.0,
   1794.0,
   1826.0,
   1856.0,
   1885.0,
   1914.0,
   1945.0,
   1974.0,
   2060.0,
   2069.0,
   2108.0,
   2129.0,
   2163.0,
   2193.0,
   2216.0,
   2230.0,
   2251.0,
   2286.0,
   2313.0,
   2347.0,
   2489.0,
   2496.0,
   2516.0,
   2590.0,
   2678.0,
   2739.0),
  (66.0,
   67.0,
   77.5,
   89.0,
   100.5,
   112.0,
   125.7,
   139.0,
   146.5,
   157.0,
   168.0,
   185.0,
   187.0,
   191.0,
   194.5,
   200.0,
   203.0,
   207.0,
   209.0,
   212.0,
   217.0,
   220.0,
   226.0,
   252.0,
   252.0,
   255.0,
   286.0,
   325.0,
   352.0)]]
In [167]:
def loadtimetable(fname:str,ncols:int)->list:
    """Loads tabulated timetable with multiple possibly empty records 
    and returns separate complete timetables.
    """
    def identity(x):return x
    array1=numpy.loadtxt(
        fname,
        delimiter='\t',
        usecols=range(ncols),
        converters={0:identity,1:identity,2:identity,3:identity},
        dtype='str'
    )
    # array1

    import matplotlib.dates
    refdatestr='20100101'
    refdate=matplotlib.dates.datestr2num(refdatestr)

    dates1=numpy.vectorize(lambda x:matplotlib.dates.datestr2num(x)-refdate)(
        array1[:,0]
    )
    # dates1

    return [list(zip(*((record[0],float(record[1])) for record in 
         list(filter(lambda x:x[-1]!='',zip(dates1,array1[:,column])))
           )))
    for column in range(1,ncols)]
In [169]:
array1=loadtimetable('compteurs.txt',4)
array1
Out[169]:
[[(1711.0,
   1787.0,
   1918.0,
   2080.0,
   2174.0,
   2220.0,
   2280.0,
   2296.0,
   2350.0,
   2367.0,
   2453.0,
   2533.0,
   2537.0,
   2609.0,
   2661.0,
   2714.0,
   2727.0),
  (49513.0,
   49674.0,
   50393.0,
   51089.0,
   51264.0,
   51385.0,
   51551.0,
   51594.0,
   51823.0,
   51888.0,
   52357.0,
   52433.0,
   52450.0,
   52711.0,
   52758.0,
   53086.0,
   53086.0)],
 [(1711.0,
   1787.0,
   1918.0,
   2080.0,
   2174.0,
   2220.0,
   2280.0,
   2296.0,
   2367.0,
   2453.0,
   2533.0,
   2609.0,
   2661.0,
   2716.0,
   2727.0),
  (145.0,
   152.0,
   194.0,
   230.0,
   235.0,
   241.0,
   249.0,
   251.0,
   310.0,
   331.0,
   332.0,
   341.0,
   343.0,
   382.0,
   384.0)],
 [(1711.0,
   1787.0,
   1918.0,
   2080.0,
   2174.0,
   2220.0,
   2280.0,
   2296.0,
   2367.0,
   2385.0,
   2453.0,
   2533.0,
   2609.0,
   2661.0,
   2727.0),
  (40.0,
   50.0,
   69.0,
   118.0,
   122.0,
   126.0,
   131.0,
   134.0,
   151.0,
   157.0,
   186.0,
   187.0,
   193.0,
   195.0,
   217.0)]]

Working on heterogeneous arrays with pandas

Numerical computing with scipy

Short names are better than import * but contexts would be better than short names.

In [170]:
import numpy as np
In [171]:
from scipy.integrate import odeint
from scipy.special import gamma, airy

y1_0 = 1.0 / 3**(2.0/3.0) / gamma(2.0/3.0)
y0_0 = -1.0 / 3**(1.0/3.0) / gamma(1.0/3.0)
y0 = [y0_0, y1_0]

def func(y, t):
     return [t*y[1],y[0]]
    
def gradient(y, t):
     return [[0,t], [1,0]]
In [172]:
x = np.arange(0, 4.0, 0.01)
t = x
ychk = airy(x)[0]
In [173]:
y = odeint(func, y0, t)
y2= odeint(func, y0, t, Dfun=gradient)
In [174]:
ychk[:36:6]
y[:36:6,1]
y2[:36:6,1]
Out[174]:
array([ 0.35502805,  0.33951139,  0.32406751,  0.30876307,  0.29365818,
        0.27880648])
Out[174]:
array([ 0.35502805,  0.33951138,  0.32406749,  0.30876306,  0.29365817,
        0.27880648])
Out[174]:
array([ 0.35502805,  0.33951138,  0.32406749,  0.30876306,  0.29365817,
        0.27880648])

Graphics

matplotlib

In [175]:
import matplotlib
%matplotlib inline
In [176]:
matplotlib.__version__
Out[176]:
'2.0.2'
In [177]:
matplotlib.pyplot.plot(t,y[:,1])
matplotlib.pyplot.plot(t,y2[:,1])
matplotlib.pyplot.plot(t,ychk)
Out[177]:
[<matplotlib.lines.Line2D at 0x11639c588>]
Out[177]:
[<matplotlib.lines.Line2D at 0x10eb06828>]
Out[177]:
[<matplotlib.lines.Line2D at 0x11639cf28>]
In [178]:
n=1000
matplotlib.pyplot.plot(
    list(random_batch(n)),list(random_batch(n)),'x',alpha=.3)
del n
Out[178]:
[<matplotlib.lines.Line2D at 0x116538710>]
In [179]:
t=numpy.arange(0.,5.,.2)
t
matplotlib.pyplot.plot(t,t**2,'r--')

del t
Out[179]:
array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,  1.4,  1.6,  1.8,  2. ,
        2.2,  2.4,  2.6,  2.8,  3. ,  3.2,  3.4,  3.6,  3.8,  4. ,  4.2,
        4.4,  4.6,  4.8])
Out[179]:
[<matplotlib.lines.Line2D at 0x116582c88>]
In [180]:
matplotlib.pyplot.plot(*[(5364.0,
  5440.0,
  5571.0,
  5733.0,
  5827.0,
  5873.0,
  5933.0,
  5949.0,
  6003.0,
  6020.0,
  6106.0,
  6186.0,
  6190.0,
  6262.0,
  6314.0,
  6367.0,
  6380.0),
 (49513.0,
  49674.0,
  50393.0,
  51089.0,
  51264.0,
  51385.0,
  51551.0,
  51594.0,
  51823.0,
  51888.0,
  52357.0,
  52433.0,
  52450.0,
  52711.0,
  52758.0,
  53086.0,
  53086.0)],'.')
Out[180]:
[<matplotlib.lines.Line2D at 0x1166b1860>]
In [182]:
timetables=loadtimetable('compteurs.txt',4)
In [183]:
for timetable in timetables:
    matplotlib.pyplot.figure()
    matplotlib.pyplot.plot(*timetable,'.')
    matplotlib.pyplot.show()  
Out[183]:
<matplotlib.figure.Figure at 0x116832208>
Out[183]:
[<matplotlib.lines.Line2D at 0x1167d54a8>]
Out[183]:
<matplotlib.figure.Figure at 0x116543358>
Out[183]:
[<matplotlib.lines.Line2D at 0x116a17748>]
Out[183]:
<matplotlib.figure.Figure at 0x116a3cd68>
Out[183]:
[<matplotlib.lines.Line2D at 0x116a5f5f8>]

LaTeX

In [184]:
from IPython.display import display, Math, Latex
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
$$F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx$$
In [185]:
display(Math(r'c = \sqrt{a^2 + b^2}'))
$$c = \sqrt{a^2 + b^2}$$
In [186]:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
Out[186]:
\begin{eqnarray} \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\ \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\ \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\ \nabla \cdot \vec{\mathbf{B}} & = 0 \end{eqnarray}
In [189]:
%%latex
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
\begin{align} \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\ \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\ \nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\ \nabla \cdot \vec{\mathbf{B}} & = 0 \end{align}

Equation used depends on whether the the value of
$V_{max}$ is R, G, or B. $\text{\LaTeX}$

turtle

In [7]:
import turtle
In [8]:
help(turtle)
Help on module turtle:

NAME
    turtle

MODULE REFERENCE
    https://docs.python.org/3.6/library/turtle
    
    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
    Turtle graphics is a popular way for introducing programming to
    kids. It was part of the original Logo programming language developed
    by Wally Feurzig and Seymour Papert in 1966.
    
    Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it
    the command turtle.forward(15), and it moves (on-screen!) 15 pixels in
    the direction it is facing, drawing a line as it moves. Give it the
    command turtle.right(25), and it rotates in-place 25 degrees clockwise.
    
    By combining together these and similar commands, intricate shapes and
    pictures can easily be drawn.
    
    ----- turtle.py
    
    This module is an extended reimplementation of turtle.py from the
    Python standard distribution up to Python 2.5. (See: http://www.python.org)
    
    It tries to keep the merits of turtle.py and to be (nearly) 100%
    compatible with it. This means in the first place to enable the
    learning programmer to use all the commands, classes and methods
    interactively when using the module from within IDLE run with
    the -n switch.
    
    Roughly it has the following features added:
    
    - Better animation of the turtle movements, especially of turning the
      turtle. So the turtles can more easily be used as a visual feedback
      instrument by the (beginning) programmer.
    
    - Different turtle shapes, gif-images as turtle shapes, user defined
      and user controllable turtle shapes, among them compound
      (multicolored) shapes. Turtle shapes can be stretched and tilted, which
      makes turtles very versatile geometrical objects.
    
    - Fine control over turtle movement and screen updates via delay(),
      and enhanced tracer() and speed() methods.
    
    - Aliases for the most commonly used commands, like fd for forward etc.,
      following the early Logo traditions. This reduces the boring work of
      typing long sequences of commands, which often occur in a natural way
      when kids try to program fancy pictures on their first encounter with
      turtle graphics.
    
    - Turtles now have an undo()-method with configurable undo-buffer.
    
    - Some simple commands/methods for creating event driven programs
      (mouse-, key-, timer-events). Especially useful for programming games.
    
    - A scrollable Canvas class. The default scrollable Canvas can be
      extended interactively as needed while playing around with the turtle(s).
    
    - A TurtleScreen class with methods controlling background color or
      background image, window and canvas size and other properties of the
      TurtleScreen.
    
    - There is a method, setworldcoordinates(), to install a user defined
      coordinate-system for the TurtleScreen.
    
    - The implementation uses a 2-vector class named Vec2D, derived from tuple.
      This class is public, so it can be imported by the application programmer,
      which makes certain types of computations very natural and compact.
    
    - Appearance of the TurtleScreen and the Turtles at startup/import can be
      configured by means of a turtle.cfg configuration file.
      The default configuration mimics the appearance of the old turtle module.
    
    - If configured appropriately the module reads in docstrings from a docstring
      dictionary in some different language, supplied separately  and replaces
      the English ones by those read in. There is a utility function
      write_docstringdict() to write a dictionary with the original (English)
      docstrings to disc, so it can serve as a template for translations.
    
    Behind the scenes there are some features included with possible
    extensions in mind. These will be commented and documented elsewhere.

CLASSES
    builtins.Exception(builtins.BaseException)
        Terminator
    builtins.object
        Shape
    builtins.tuple(builtins.object)
        Vec2D
    tkinter.Frame(tkinter.Widget)
        ScrolledCanvas
    TNavigator(builtins.object)
        RawTurtle(TPen, TNavigator)
            Turtle
    TPen(builtins.object)
        RawTurtle(TPen, TNavigator)
            Turtle
    TurtleScreenBase(builtins.object)
        TurtleScreen
    
    Pen = class Turtle(RawTurtle)
     |  RawTurtle auto-creating (scrolled) canvas.
     |  
     |  When a Turtle object is created or a function derived from some
     |  Turtle method is called a TurtleScreen object is automatically created.
     |  
     |  Method resolution order:
     |      Turtle
     |      RawTurtle
     |      TPen
     |      TNavigator
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, shape='classic', undobuffersize=1000, visible=True)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from RawTurtle:
     |  
     |  begin_fill(self)
     |      Called just before drawing a shape to be filled.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("black", "red")
     |      >>> turtle.begin_fill()
     |      >>> turtle.circle(60)
     |      >>> turtle.end_fill()
     |  
     |  begin_poly(self)
     |      Start recording the vertices of a polygon.
     |      
     |      No argument.
     |      
     |      Start recording the vertices of a polygon. Current turtle position
     |      is first point of polygon.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.begin_poly()
     |  
     |  clear(self)
     |      Delete the turtle's drawings from the screen. Do not move turtle.
     |      
     |      No arguments.
     |      
     |      Delete the turtle's drawings from the screen. Do not move turtle.
     |      State and position of the turtle as well as drawings of other
     |      turtles are not affected.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.clear()
     |  
     |  clearstamp(self, stampid)
     |      Delete stamp with given stampid
     |      
     |      Argument:
     |      stampid - an integer, must be return value of previous stamp() call.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("blue")
     |      >>> astamp = turtle.stamp()
     |      >>> turtle.fd(50)
     |      >>> turtle.clearstamp(astamp)
     |  
     |  clearstamps(self, n=None)
     |      Delete all or first/last n of turtle's stamps.
     |      
     |      Optional argument:
     |      n -- an integer
     |      
     |      If n is None, delete all of pen's stamps,
     |      else if n > 0 delete first n stamps
     |      else if n < 0 delete last n stamps.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> for i in range(8):
     |      ...     turtle.stamp(); turtle.fd(30)
     |      ...
     |      >>> turtle.clearstamps(2)
     |      >>> turtle.clearstamps(-2)
     |      >>> turtle.clearstamps()
     |  
     |  clone(self)
     |      Create and return a clone of the turtle.
     |      
     |      No argument.
     |      
     |      Create and return a clone of the turtle with same position, heading
     |      and turtle properties.
     |      
     |      Example (for a Turtle instance named mick):
     |      mick = Turtle()
     |      joe = mick.clone()
     |  
     |  dot(self, size=None, *color)
     |      Draw a dot with diameter size, using color.
     |      
     |      Optional arguments:
     |      size -- an integer >= 1 (if given)
     |      color -- a colorstring or a numeric color tuple
     |      
     |      Draw a circular dot with diameter size, using color.
     |      If size is not given, the maximum of pensize+4 and 2*pensize is used.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.dot()
     |      >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
     |  
     |  end_fill(self)
     |      Fill the shape drawn after the call begin_fill().
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("black", "red")
     |      >>> turtle.begin_fill()
     |      >>> turtle.circle(60)
     |      >>> turtle.end_fill()
     |  
     |  end_poly(self)
     |      Stop recording the vertices of a polygon.
     |      
     |      No argument.
     |      
     |      Stop recording the vertices of a polygon. Current turtle position is
     |      last point of polygon. This will be connected with the first point.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.end_poly()
     |  
     |  filling(self)
     |      Return fillstate (True if filling, False else).
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.begin_fill()
     |      >>> if turtle.filling():
     |      ...     turtle.pensize(5)
     |      ... else:
     |      ...     turtle.pensize(3)
     |  
     |  get_poly(self)
     |      Return the lastly recorded polygon.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> p = turtle.get_poly()
     |      >>> turtle.register_shape("myFavouriteShape", p)
     |  
     |  get_shapepoly(self)
     |      Return the current shape polygon as tuple of coordinate pairs.
     |      
     |      No argument.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("square")
     |      >>> turtle.shapetransform(4, -1, 0, 2)
     |      >>> turtle.get_shapepoly()
     |      ((50, -20), (30, 20), (-50, 20), (-30, -20))
     |  
     |  getpen = getturtle(self)
     |      Return the Turtleobject itself.
     |      
     |      No argument.
     |      
     |      Only reasonable use: as a function to return the 'anonymous turtle':
     |      
     |      Example:
     |      >>> pet = getturtle()
     |      >>> pet.fd(50)
     |      >>> pet
     |      <turtle.Turtle object at 0x0187D810>
     |      >>> turtles()
     |      [<turtle.Turtle object at 0x0187D810>]
     |  
     |  getscreen(self)
     |      Return the TurtleScreen object, the turtle is drawing  on.
     |      
     |      No argument.
     |      
     |      Return the TurtleScreen object, the turtle is drawing  on.
     |      So TurtleScreen-methods can be called for that object.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> ts = turtle.getscreen()
     |      >>> ts
     |      <turtle.TurtleScreen object at 0x0106B770>
     |      >>> ts.bgcolor("pink")
     |  
     |  getturtle(self)
     |      Return the Turtleobject itself.
     |      
     |      No argument.
     |      
     |      Only reasonable use: as a function to return the 'anonymous turtle':
     |      
     |      Example:
     |      >>> pet = getturtle()
     |      >>> pet.fd(50)
     |      >>> pet
     |      <turtle.Turtle object at 0x0187D810>
     |      >>> turtles()
     |      [<turtle.Turtle object at 0x0187D810>]
     |  
     |  onclick(self, fun, btn=1, add=None)
     |      Bind fun to mouse-click event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun --  a function with two arguments, to which will be assigned
     |              the coordinates of the clicked point on the canvas.
     |      num --  number of the mouse-button defaults to 1 (left mouse button).
     |      add --  True or False. If True, new binding will be added, otherwise
     |              it will replace a former binding.
     |      
     |      Example for the anonymous turtle, i. e. the procedural way:
     |      
     |      >>> def turn(x, y):
     |      ...     left(360)
     |      ...
     |      >>> onclick(turn)  # Now clicking into the turtle will turn it.
     |      >>> onclick(None)  # event-binding will be removed
     |  
     |  ondrag(self, fun, btn=1, add=None)
     |      Bind fun to mouse-move event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun -- a function with two arguments, to which will be assigned
     |             the coordinates of the clicked point on the canvas.
     |      num -- number of the mouse-button defaults to 1 (left mouse button).
     |      
     |      Every sequence of mouse-move-events on a turtle is preceded by a
     |      mouse-click event on that turtle.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.ondrag(turtle.goto)
     |      
     |      Subsequently clicking and dragging a Turtle will move it
     |      across the screen thereby producing handdrawings (if pen is
     |      down).
     |  
     |  onrelease(self, fun, btn=1, add=None)
     |      Bind fun to mouse-button-release event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun -- a function with two arguments, to which will be assigned
     |              the coordinates of the clicked point on the canvas.
     |      num --  number of the mouse-button defaults to 1 (left mouse button).
     |      
     |      Example (for a MyTurtle instance named joe):
     |      >>> class MyTurtle(Turtle):
     |      ...     def glow(self,x,y):
     |      ...             self.fillcolor("red")
     |      ...     def unglow(self,x,y):
     |      ...             self.fillcolor("")
     |      ...
     |      >>> joe = MyTurtle()
     |      >>> joe.onclick(joe.glow)
     |      >>> joe.onrelease(joe.unglow)
     |      
     |      Clicking on joe turns fillcolor red, unclicking turns it to
     |      transparent.
     |  
     |  reset(self)
     |      Delete the turtle's drawings and restore its default values.
     |      
     |      No argument.
     |      
     |      Delete the turtle's drawings from the screen, re-center the turtle
     |      and set variables to the default values.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00,-22.00)
     |      >>> turtle.heading()
     |      100.0
     |      >>> turtle.reset()
     |      >>> turtle.position()
     |      (0.00,0.00)
     |      >>> turtle.heading()
     |      0.0
     |  
     |  settiltangle(self, angle)
     |      Rotate the turtleshape to point in the specified direction
     |      
     |      Argument: angle -- number
     |      
     |      Rotate the turtleshape to point in the direction specified by angle,
     |      regardless of its current tilt-angle. DO NOT change the turtle's
     |      heading (direction of movement).
     |      
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.settiltangle(45)
     |      >>> stamp()
     |      >>> turtle.fd(50)
     |      >>> turtle.settiltangle(-45)
     |      >>> stamp()
     |      >>> turtle.fd(50)
     |  
     |  setundobuffer(self, size)
     |      Set or disable undobuffer.
     |      
     |      Argument:
     |      size -- an integer or None
     |      
     |      If size is an integer an empty undobuffer of given size is installed.
     |      Size gives the maximum number of turtle-actions that can be undone
     |      by the undo() function.
     |      If size is None, no undobuffer is present.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.setundobuffer(42)
     |  
     |  shape(self, name=None)
     |      Set turtle shape to shape with given name / return current shapename.
     |      
     |      Optional argument:
     |      name -- a string, which is a valid shapename
     |      
     |      Set turtle shape to shape with given name or, if name is not given,
     |      return name of current shape.
     |      Shape with name must exist in the TurtleScreen's shape dictionary.
     |      Initially there are the following polygon shapes:
     |      'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'.
     |      To learn about how to deal with shapes see Screen-method register_shape.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.shape()
     |      'arrow'
     |      >>> turtle.shape("turtle")
     |      >>> turtle.shape()
     |      'turtle'
     |  
     |  shapesize(self, stretch_wid=None, stretch_len=None, outline=None)
     |      Set/return turtle's stretchfactors/outline. Set resizemode to "user".
     |      
     |      Optional arguments:
     |         stretch_wid : positive number
     |         stretch_len : positive number
     |         outline  : positive number
     |      
     |      Return or set the pen's attributes x/y-stretchfactors and/or outline.
     |      Set resizemode to "user".
     |      If and only if resizemode is set to "user", the turtle will be displayed
     |      stretched according to its stretchfactors:
     |      stretch_wid is stretchfactor perpendicular to orientation
     |      stretch_len is stretchfactor in direction of turtles orientation.
     |      outline determines the width of the shapes's outline.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.resizemode("user")
     |      >>> turtle.shapesize(5, 5, 12)
     |      >>> turtle.shapesize(outline=8)
     |  
     |  shapetransform(self, t11=None, t12=None, t21=None, t22=None)
     |      Set or return the current transformation matrix of the turtle shape.
     |      
     |      Optional arguments: t11, t12, t21, t22 -- numbers.
     |      
     |      If none of the matrix elements are given, return the transformation
     |      matrix.
     |      Otherwise set the given elements and transform the turtleshape
     |      according to the matrix consisting of first row t11, t12 and
     |      second row t21, 22.
     |      Modify stretchfactor, shearfactor and tiltangle according to the
     |      given matrix.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("square")
     |      >>> turtle.shapesize(4,2)
     |      >>> turtle.shearfactor(-0.5)
     |      >>> turtle.shapetransform()
     |      (4.0, -1.0, -0.0, 2.0)
     |  
     |  shearfactor(self, shear=None)
     |      Set or return the current shearfactor.
     |      
     |      Optional argument: shear -- number, tangent of the shear angle
     |      
     |      Shear the turtleshape according to the given shearfactor shear,
     |      which is the tangent of the shear angle. DO NOT change the
     |      turtle's heading (direction of movement).
     |      If shear is not given: return the current shearfactor, i. e. the
     |      tangent of the shear angle, by which lines parallel to the
     |      heading of the turtle are sheared.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.shearfactor(0.5)
     |      >>> turtle.shearfactor()
     |      >>> 0.5
     |  
     |  stamp(self)
     |      Stamp a copy of the turtleshape onto the canvas and return its id.
     |      
     |      No argument.
     |      
     |      Stamp a copy of the turtle shape onto the canvas at the current
     |      turtle position. Return a stamp_id for that stamp, which can be
     |      used to delete it by calling clearstamp(stamp_id).
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("blue")
     |      >>> turtle.stamp()
     |      13
     |      >>> turtle.fd(50)
     |  
     |  tilt(self, angle)
     |      Rotate the turtleshape by angle.
     |      
     |      Argument:
     |      angle - a number
     |      
     |      Rotate the turtleshape by angle from its current tilt-angle,
     |      but do NOT change the turtle's heading (direction of movement).
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.tilt(30)
     |      >>> turtle.fd(50)
     |      >>> turtle.tilt(30)
     |      >>> turtle.fd(50)
     |  
     |  tiltangle(self, angle=None)
     |      Set or return the current tilt-angle.
     |      
     |      Optional argument: angle -- number
     |      
     |      Rotate the turtleshape to point in the direction specified by angle,
     |      regardless of its current tilt-angle. DO NOT change the turtle's
     |      heading (direction of movement).
     |      If angle is not given: return the current tilt-angle, i. e. the angle
     |      between the orientation of the turtleshape and the heading of the
     |      turtle (its direction of movement).
     |      
     |      Deprecated since Python 3.1
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.tilt(45)
     |      >>> turtle.tiltangle()
     |  
     |  turtlesize = shapesize(self, stretch_wid=None, stretch_len=None, outline=None)
     |      Set/return turtle's stretchfactors/outline. Set resizemode to "user".
     |      
     |      Optional arguments:
     |         stretch_wid : positive number
     |         stretch_len : positive number
     |         outline  : positive number
     |      
     |      Return or set the pen's attributes x/y-stretchfactors and/or outline.
     |      Set resizemode to "user".
     |      If and only if resizemode is set to "user", the turtle will be displayed
     |      stretched according to its stretchfactors:
     |      stretch_wid is stretchfactor perpendicular to orientation
     |      stretch_len is stretchfactor in direction of turtles orientation.
     |      outline determines the width of the shapes's outline.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.resizemode("user")
     |      >>> turtle.shapesize(5, 5, 12)
     |      >>> turtle.shapesize(outline=8)
     |  
     |  undo(self)
     |      undo (repeatedly) the last turtle action.
     |      
     |      No argument.
     |      
     |      undo (repeatedly) the last turtle action.
     |      Number of available undo actions is determined by the size of
     |      the undobuffer.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> for i in range(4):
     |      ...     turtle.fd(50); turtle.lt(80)
     |      ...
     |      >>> for i in range(8):
     |      ...     turtle.undo()
     |      ...
     |  
     |  undobufferentries(self)
     |      Return count of entries in the undobuffer.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> while undobufferentries():
     |      ...     undo()
     |  
     |  write(self, arg, move=False, align='left', font=('Arial', 8, 'normal'))
     |      Write text at the current turtle position.
     |      
     |      Arguments:
     |      arg -- info, which is to be written to the TurtleScreen
     |      move (optional) -- True/False
     |      align (optional) -- one of the strings "left", "center" or right"
     |      font (optional) -- a triple (fontname, fontsize, fonttype)
     |      
     |      Write text - the string representation of arg - at the current
     |      turtle position according to align ("left", "center" or right")
     |      and with the given font.
     |      If move is True, the pen is moved to the bottom-right corner
     |      of the text. By default, move is False.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.write('Home = ', True, align="center")
     |      >>> turtle.write((0,0), True)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from RawTurtle:
     |  
     |  screens = []
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from TPen:
     |  
     |  color(self, *args)
     |      Return or set the pencolor and fillcolor.
     |      
     |      Arguments:
     |      Several input formats are allowed.
     |      They use 0, 1, 2, or 3 arguments as follows:
     |      
     |      color()
     |          Return the current pencolor and the current fillcolor
     |          as a pair of color specification strings as are returned
     |          by pencolor and fillcolor.
     |      color(colorstring), color((r,g,b)), color(r,g,b)
     |          inputs as in pencolor, set both, fillcolor and pencolor,
     |          to the given value.
     |      color(colorstring1, colorstring2),
     |      color((r1,g1,b1), (r2,g2,b2))
     |          equivalent to pencolor(colorstring1) and fillcolor(colorstring2)
     |          and analogously, if the other input format is used.
     |      
     |      If turtleshape is a polygon, outline and interior of that polygon
     |      is drawn with the newly set colors.
     |      For mor info see: pencolor, fillcolor
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color('red', 'green')
     |      >>> turtle.color()
     |      ('red', 'green')
     |      >>> colormode(255)
     |      >>> color((40, 80, 120), (160, 200, 240))
     |      >>> color()
     |      ('#285078', '#a0c8f0')
     |  
     |  down = pendown(self)
     |      Pull the pen down -- drawing when moving.
     |      
     |      Aliases: pendown | pd | down
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pendown()
     |  
     |  fillcolor(self, *args)
     |      Return or set the fillcolor.
     |      
     |      Arguments:
     |      Four input formats are allowed:
     |        - fillcolor()
     |          Return the current fillcolor as color specification string,
     |          possibly in hex-number format (see example).
     |          May be used as input to another color/pencolor/fillcolor call.
     |        - fillcolor(colorstring)
     |          s is a Tk color specification string, such as "red" or "yellow"
     |        - fillcolor((r, g, b))
     |          *a tuple* of r, g, and b, which represent, an RGB color,
     |          and each of r, g, and b are in the range 0..colormode,
     |          where colormode is either 1.0 or 255
     |        - fillcolor(r, g, b)
     |          r, g, and b represent an RGB color, and each of r, g, and b
     |          are in the range 0..colormode
     |      
     |      If turtleshape is a polygon, the interior of that polygon is drawn
     |      with the newly set fillcolor.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.fillcolor('violet')
     |      >>> col = turtle.pencolor()
     |      >>> turtle.fillcolor(col)
     |      >>> turtle.fillcolor(0, .5, 0)
     |  
     |  hideturtle(self)
     |      Makes the turtle invisible.
     |      
     |      Aliases: hideturtle | ht
     |      
     |      No argument.
     |      
     |      It's a good idea to do this while you're in the
     |      middle of a complicated drawing, because hiding
     |      the turtle speeds up the drawing observably.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |  
     |  ht = hideturtle(self)
     |      Makes the turtle invisible.
     |      
     |      Aliases: hideturtle | ht
     |      
     |      No argument.
     |      
     |      It's a good idea to do this while you're in the
     |      middle of a complicated drawing, because hiding
     |      the turtle speeds up the drawing observably.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |  
     |  isdown(self)
     |      Return True if pen is down, False if it's up.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |      >>> turtle.isdown()
     |      False
     |      >>> turtle.pendown()
     |      >>> turtle.isdown()
     |      True
     |  
     |  isvisible(self)
     |      Return True if the Turtle is shown, False if it's hidden.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |      >>> print turtle.isvisible():
     |      False
     |  
     |  pd = pendown(self)
     |      Pull the pen down -- drawing when moving.
     |      
     |      Aliases: pendown | pd | down
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pendown()
     |  
     |  pen(self, pen=None, **pendict)
     |      Return or set the pen's attributes.
     |      
     |      Arguments:
     |          pen -- a dictionary with some or all of the below listed keys.
     |          **pendict -- one or more keyword-arguments with the below
     |                       listed keys as keywords.
     |      
     |      Return or set the pen's attributes in a 'pen-dictionary'
     |      with the following key/value pairs:
     |         "shown"      :   True/False
     |         "pendown"    :   True/False
     |         "pencolor"   :   color-string or color-tuple
     |         "fillcolor"  :   color-string or color-tuple
     |         "pensize"    :   positive number
     |         "speed"      :   number in range 0..10
     |         "resizemode" :   "auto" or "user" or "noresize"
     |         "stretchfactor": (positive number, positive number)
     |         "shearfactor":   number
     |         "outline"    :   positive number
     |         "tilt"       :   number
     |      
     |      This dictionary can be used as argument for a subsequent
     |      pen()-call to restore the former pen-state. Moreover one
     |      or more of these attributes can be provided as keyword-arguments.
     |      This can be used to set several pen attributes in one statement.
     |      
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
     |      >>> turtle.pen()
     |      {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
     |      'pencolor': 'red', 'pendown': True, 'fillcolor': 'black',
     |      'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
     |      >>> penstate=turtle.pen()
     |      >>> turtle.color("yellow","")
     |      >>> turtle.penup()
     |      >>> turtle.pen()
     |      {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
     |      'pencolor': 'yellow', 'pendown': False, 'fillcolor': '',
     |      'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
     |      >>> p.pen(penstate, fillcolor="green")
     |      >>> p.pen()
     |      {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
     |      'pencolor': 'red', 'pendown': True, 'fillcolor': 'green',
     |      'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
     |  
     |  pencolor(self, *args)
     |      Return or set the pencolor.
     |      
     |      Arguments:
     |      Four input formats are allowed:
     |        - pencolor()
     |          Return the current pencolor as color specification string,
     |          possibly in hex-number format (see example).
     |          May be used as input to another color/pencolor/fillcolor call.
     |        - pencolor(colorstring)
     |          s is a Tk color specification string, such as "red" or "yellow"
     |        - pencolor((r, g, b))
     |          *a tuple* of r, g, and b, which represent, an RGB color,
     |          and each of r, g, and b are in the range 0..colormode,
     |          where colormode is either 1.0 or 255
     |        - pencolor(r, g, b)
     |          r, g, and b represent an RGB color, and each of r, g, and b
     |          are in the range 0..colormode
     |      
     |      If turtleshape is a polygon, the outline of that polygon is drawn
     |      with the newly set pencolor.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pencolor('brown')
     |      >>> tup = (0.2, 0.8, 0.55)
     |      >>> turtle.pencolor(tup)
     |      >>> turtle.pencolor()
     |      '#33cc8c'
     |  
     |  pendown(self)
     |      Pull the pen down -- drawing when moving.
     |      
     |      Aliases: pendown | pd | down
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pendown()
     |  
     |  pensize(self, width=None)
     |      Set or return the line thickness.
     |      
     |      Aliases:  pensize | width
     |      
     |      Argument:
     |      width -- positive number
     |      
     |      Set the line thickness to width or return it. If resizemode is set
     |      to "auto" and turtleshape is a polygon, that polygon is drawn with
     |      the same line thickness. If no argument is given, current pensize
     |      is returned.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pensize()
     |      1
     |      >>> turtle.pensize(10)   # from here on lines of width 10 are drawn
     |  
     |  penup(self)
     |      Pull the pen up -- no drawing when moving.
     |      
     |      Aliases: penup | pu | up
     |      
     |      No argument
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |  
     |  pu = penup(self)
     |      Pull the pen up -- no drawing when moving.
     |      
     |      Aliases: penup | pu | up
     |      
     |      No argument
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |  
     |  resizemode(self, rmode=None)
     |      Set resizemode to one of the values: "auto", "user", "noresize".
     |      
     |      (Optional) Argument:
     |      rmode -- one of the strings "auto", "user", "noresize"
     |      
     |      Different resizemodes have the following effects:
     |        - "auto" adapts the appearance of the turtle
     |                 corresponding to the value of pensize.
     |        - "user" adapts the appearance of the turtle according to the
     |                 values of stretchfactor and outlinewidth (outline),
     |                 which are set by shapesize()
     |        - "noresize" no adaption of the turtle's appearance takes place.
     |      If no argument is given, return current resizemode.
     |      resizemode("user") is called by a call of shapesize with arguments.
     |      
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.resizemode("noresize")
     |      >>> turtle.resizemode()
     |      'noresize'
     |  
     |  showturtle(self)
     |      Makes the turtle visible.
     |      
     |      Aliases: showturtle | st
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |      >>> turtle.showturtle()
     |  
     |  speed(self, speed=None)
     |      Return or set the turtle's speed.
     |      
     |      Optional argument:
     |      speed -- an integer in the range 0..10 or a speedstring (see below)
     |      
     |      Set the turtle's speed to an integer value in the range 0 .. 10.
     |      If no argument is given: return current speed.
     |      
     |      If input is a number greater than 10 or smaller than 0.5,
     |      speed is set to 0.
     |      Speedstrings  are mapped to speedvalues in the following way:
     |          'fastest' :  0
     |          'fast'    :  10
     |          'normal'  :  6
     |          'slow'    :  3
     |          'slowest' :  1
     |      speeds from 1 to 10 enforce increasingly faster animation of
     |      line drawing and turtle turning.
     |      
     |      Attention:
     |      speed = 0 : *no* animation takes place. forward/back makes turtle jump
     |      and likewise left/right make the turtle turn instantly.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.speed(3)
     |  
     |  st = showturtle(self)
     |      Makes the turtle visible.
     |      
     |      Aliases: showturtle | st
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |      >>> turtle.showturtle()
     |  
     |  up = penup(self)
     |      Pull the pen up -- no drawing when moving.
     |      
     |      Aliases: penup | pu | up
     |      
     |      No argument
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |  
     |  width = pensize(self, width=None)
     |      Set or return the line thickness.
     |      
     |      Aliases:  pensize | width
     |      
     |      Argument:
     |      width -- positive number
     |      
     |      Set the line thickness to width or return it. If resizemode is set
     |      to "auto" and turtleshape is a polygon, that polygon is drawn with
     |      the same line thickness. If no argument is given, current pensize
     |      is returned.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pensize()
     |      1
     |      >>> turtle.pensize(10)   # from here on lines of width 10 are drawn
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from TPen:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from TNavigator:
     |  
     |  back(self, distance)
     |      Move the turtle backward by distance.
     |      
     |      Aliases: back | backward | bk
     |      
     |      Argument:
     |      distance -- a number
     |      
     |      Move the turtle backward by distance ,opposite to the direction the
     |      turtle is headed. Do not change the turtle's heading.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.backward(30)
     |      >>> turtle.position()
     |      (-30.00, 0.00)
     |  
     |  backward = back(self, distance)
     |      Move the turtle backward by distance.
     |      
     |      Aliases: back | backward | bk
     |      
     |      Argument:
     |      distance -- a number
     |      
     |      Move the turtle backward by distance ,opposite to the direction the
     |      turtle is headed. Do not change the turtle's heading.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.backward(30)
     |      >>> turtle.position()
     |      (-30.00, 0.00)
     |  
     |  bk = back(self, distance)
     |      Move the turtle backward by distance.
     |      
     |      Aliases: back | backward | bk
     |      
     |      Argument:
     |      distance -- a number
     |      
     |      Move the turtle backward by distance ,opposite to the direction the
     |      turtle is headed. Do not change the turtle's heading.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.backward(30)
     |      >>> turtle.position()
     |      (-30.00, 0.00)
     |  
     |  circle(self, radius, extent=None, steps=None)
     |      Draw a circle with given radius.
     |      
     |      Arguments:
     |      radius -- a number
     |      extent (optional) -- a number
     |      steps (optional) -- an integer
     |      
     |      Draw a circle with given radius. The center is radius units left
     |      of the turtle; extent - an angle - determines which part of the
     |      circle is drawn. If extent is not given, draw the entire circle.
     |      If extent is not a full circle, one endpoint of the arc is the
     |      current pen position. Draw the arc in counterclockwise direction
     |      if radius is positive, otherwise in clockwise direction. Finally
     |      the direction of the turtle is changed by the amount of extent.
     |      
     |      As the circle is approximated by an inscribed regular polygon,
     |      steps determines the number of steps to use. If not given,
     |      it will be calculated automatically. Maybe used to draw regular
     |      polygons.
     |      
     |      call: circle(radius)                  # full circle
     |      --or: circle(radius, extent)          # arc
     |      --or: circle(radius, extent, steps)
     |      --or: circle(radius, steps=6)         # 6-sided polygon
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.circle(50)
     |      >>> turtle.circle(120, 180)  # semicircle
     |  
     |  degrees(self, fullcircle=360.0)
     |      Set angle measurement units to degrees.
     |      
     |      Optional argument:
     |      fullcircle -  a number
     |      
     |      Set angle measurement units, i. e. set number
     |      of 'degrees' for a full circle. Dafault value is
     |      360 degrees.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.left(90)
     |      >>> turtle.heading()
     |      90
     |      
     |      Change angle measurement unit to grad (also known as gon,
     |      grade, or gradian and equals 1/100-th of the right angle.)
     |      >>> turtle.degrees(400.0)
     |      >>> turtle.heading()
     |      100
     |  
     |  distance(self, x, y=None)
     |      Return the distance from the turtle to (x,y) in turtle step units.
     |      
     |      Arguments:
     |      x -- a number   or  a pair/vector of numbers   or   a turtle instance
     |      y -- a number       None                            None
     |      
     |      call: distance(x, y)         # two coordinates
     |      --or: distance((x, y))       # a pair (tuple) of coordinates
     |      --or: distance(vec)          # e.g. as returned by pos()
     |      --or: distance(mypen)        # where mypen is another turtle
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (0.00, 0.00)
     |      >>> turtle.distance(30,40)
     |      50.0
     |      >>> pen = Turtle()
     |      >>> pen.forward(77)
     |      >>> turtle.distance(pen)
     |      77.0
     |  
     |  fd = forward(self, distance)
     |      Move the turtle forward by the specified distance.
     |      
     |      Aliases: forward | fd
     |      
     |      Argument:
     |      distance -- a number (integer or float)
     |      
     |      Move the turtle forward by the specified distance, in the direction
     |      the turtle is headed.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.forward(25)
     |      >>> turtle.position()
     |      (25.00,0.00)
     |      >>> turtle.forward(-75)
     |      >>> turtle.position()
     |      (-50.00,0.00)
     |  
     |  forward(self, distance)
     |      Move the turtle forward by the specified distance.
     |      
     |      Aliases: forward | fd
     |      
     |      Argument:
     |      distance -- a number (integer or float)
     |      
     |      Move the turtle forward by the specified distance, in the direction
     |      the turtle is headed.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.forward(25)
     |      >>> turtle.position()
     |      (25.00,0.00)
     |      >>> turtle.forward(-75)
     |      >>> turtle.position()
     |      (-50.00,0.00)
     |  
     |  goto(self, x, y=None)
     |      Move turtle to an absolute position.
     |      
     |      Aliases: setpos | setposition | goto:
     |      
     |      Arguments:
     |      x -- a number      or     a pair/vector of numbers
     |      y -- a number             None
     |      
     |      call: goto(x, y)         # two coordinates
     |      --or: goto((x, y))       # a pair (tuple) of coordinates
     |      --or: goto(vec)          # e.g. as returned by pos()
     |      
     |      Move turtle to an absolute position. If the pen is down,
     |      a line will be drawn. The turtle's orientation does not change.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> tp = turtle.pos()
     |      >>> tp
     |      (0.00, 0.00)
     |      >>> turtle.setpos(60,30)
     |      >>> turtle.pos()
     |      (60.00,30.00)
     |      >>> turtle.setpos((20,80))
     |      >>> turtle.pos()
     |      (20.00,80.00)
     |      >>> turtle.setpos(tp)
     |      >>> turtle.pos()
     |      (0.00,0.00)
     |  
     |  heading(self)
     |      Return the turtle's current heading.
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.left(67)
     |      >>> turtle.heading()
     |      67.0
     |  
     |  home(self)
     |      Move turtle to the origin - coordinates (0,0).
     |      
     |      No arguments.
     |      
     |      Move turtle to the origin - coordinates (0,0) and set its
     |      heading to its start-orientation (which depends on mode).
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.home()
     |  
     |  left(self, angle)
     |      Turn turtle left by angle units.
     |      
     |      Aliases: left | lt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle left by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.left(45)
     |      >>> turtle.heading()
     |      67.0
     |  
     |  lt = left(self, angle)
     |      Turn turtle left by angle units.
     |      
     |      Aliases: left | lt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle left by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.left(45)
     |      >>> turtle.heading()
     |      67.0
     |  
     |  pos(self)
     |      Return the turtle's current location (x,y), as a Vec2D-vector.
     |      
     |      Aliases: pos | position
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (0.00, 240.00)
     |  
     |  position = pos(self)
     |      Return the turtle's current location (x,y), as a Vec2D-vector.
     |      
     |      Aliases: pos | position
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (0.00, 240.00)
     |  
     |  radians(self)
     |      Set the angle measurement units to radians.
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      90
     |      >>> turtle.radians()
     |      >>> turtle.heading()
     |      1.5707963267948966
     |  
     |  right(self, angle)
     |      Turn turtle right by angle units.
     |      
     |      Aliases: right | rt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle right by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.right(45)
     |      >>> turtle.heading()
     |      337.0
     |  
     |  rt = right(self, angle)
     |      Turn turtle right by angle units.
     |      
     |      Aliases: right | rt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle right by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.right(45)
     |      >>> turtle.heading()
     |      337.0
     |  
     |  seth = setheading(self, to_angle)
     |      Set the orientation of the turtle to to_angle.
     |      
     |      Aliases:  setheading | seth
     |      
     |      Argument:
     |      to_angle -- a number (integer or float)
     |      
     |      Set the orientation of the turtle to to_angle.
     |      Here are some common directions in degrees:
     |      
     |       standard - mode:          logo-mode:
     |      -------------------|--------------------
     |         0 - east                0 - north
     |        90 - north              90 - east
     |       180 - west              180 - south
     |       270 - south             270 - west
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.setheading(90)
     |      >>> turtle.heading()
     |      90
     |  
     |  setheading(self, to_angle)
     |      Set the orientation of the turtle to to_angle.
     |      
     |      Aliases:  setheading | seth
     |      
     |      Argument:
     |      to_angle -- a number (integer or float)
     |      
     |      Set the orientation of the turtle to to_angle.
     |      Here are some common directions in degrees:
     |      
     |       standard - mode:          logo-mode:
     |      -------------------|--------------------
     |         0 - east                0 - north
     |        90 - north              90 - east
     |       180 - west              180 - south
     |       270 - south             270 - west
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.setheading(90)
     |      >>> turtle.heading()
     |      90
     |  
     |  setpos = goto(self, x, y=None)
     |      Move turtle to an absolute position.
     |      
     |      Aliases: setpos | setposition | goto:
     |      
     |      Arguments:
     |      x -- a number      or     a pair/vector of numbers
     |      y -- a number             None
     |      
     |      call: goto(x, y)         # two coordinates
     |      --or: goto((x, y))       # a pair (tuple) of coordinates
     |      --or: goto(vec)          # e.g. as returned by pos()
     |      
     |      Move turtle to an absolute position. If the pen is down,
     |      a line will be drawn. The turtle's orientation does not change.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> tp = turtle.pos()
     |      >>> tp
     |      (0.00, 0.00)
     |      >>> turtle.setpos(60,30)
     |      >>> turtle.pos()
     |      (60.00,30.00)
     |      >>> turtle.setpos((20,80))
     |      >>> turtle.pos()
     |      (20.00,80.00)
     |      >>> turtle.setpos(tp)
     |      >>> turtle.pos()
     |      (0.00,0.00)
     |  
     |  setposition = goto(self, x, y=None)
     |      Move turtle to an absolute position.
     |      
     |      Aliases: setpos | setposition | goto:
     |      
     |      Arguments:
     |      x -- a number      or     a pair/vector of numbers
     |      y -- a number             None
     |      
     |      call: goto(x, y)         # two coordinates
     |      --or: goto((x, y))       # a pair (tuple) of coordinates
     |      --or: goto(vec)          # e.g. as returned by pos()
     |      
     |      Move turtle to an absolute position. If the pen is down,
     |      a line will be drawn. The turtle's orientation does not change.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> tp = turtle.pos()
     |      >>> tp
     |      (0.00, 0.00)
     |      >>> turtle.setpos(60,30)
     |      >>> turtle.pos()
     |      (60.00,30.00)
     |      >>> turtle.setpos((20,80))
     |      >>> turtle.pos()
     |      (20.00,80.00)
     |      >>> turtle.setpos(tp)
     |      >>> turtle.pos()
     |      (0.00,0.00)
     |  
     |  setx(self, x)
     |      Set the turtle's first coordinate to x
     |      
     |      Argument:
     |      x -- a number (integer or float)
     |      
     |      Set the turtle's first coordinate to x, leave second coordinate
     |      unchanged.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 240.00)
     |      >>> turtle.setx(10)
     |      >>> turtle.position()
     |      (10.00, 240.00)
     |  
     |  sety(self, y)
     |      Set the turtle's second coordinate to y
     |      
     |      Argument:
     |      y -- a number (integer or float)
     |      
     |      Set the turtle's first coordinate to x, second coordinate remains
     |      unchanged.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 40.00)
     |      >>> turtle.sety(-10)
     |      >>> turtle.position()
     |      (0.00, -10.00)
     |  
     |  towards(self, x, y=None)
     |      Return the angle of the line from the turtle's position to (x, y).
     |      
     |      Arguments:
     |      x -- a number   or  a pair/vector of numbers   or   a turtle instance
     |      y -- a number       None                            None
     |      
     |      call: distance(x, y)         # two coordinates
     |      --or: distance((x, y))       # a pair (tuple) of coordinates
     |      --or: distance(vec)          # e.g. as returned by pos()
     |      --or: distance(mypen)        # where mypen is another turtle
     |      
     |      Return the angle, between the line from turtle-position to position
     |      specified by x, y and the turtle's start orientation. (Depends on
     |      modes - "standard" or "logo")
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (10.00, 10.00)
     |      >>> turtle.towards(0,0)
     |      225.0
     |  
     |  xcor(self)
     |      Return the turtle's x coordinate.
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> reset()
     |      >>> turtle.left(60)
     |      >>> turtle.forward(100)
     |      >>> print turtle.xcor()
     |      50.0
     |  
     |  ycor(self)
     |      Return the turtle's y coordinate
     |      ---
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> reset()
     |      >>> turtle.left(60)
     |      >>> turtle.forward(100)
     |      >>> print turtle.ycor()
     |      86.6025403784
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from TNavigator:
     |  
     |  DEFAULT_ANGLEOFFSET = 0
     |  
     |  DEFAULT_ANGLEORIENT = 1
     |  
     |  DEFAULT_MODE = 'standard'
     |  
     |  START_ORIENTATION = {'logo': (0.00,1.00), 'standard': (1.00,0.00), 'wo...
    
    RawPen = class RawTurtle(TPen, TNavigator)
     |  Animation part of the RawTurtle.
     |  Puts RawTurtle upon a TurtleScreen and provides tools for
     |  its animation.
     |  
     |  Method resolution order:
     |      RawTurtle
     |      TPen
     |      TNavigator
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, canvas=None, shape='classic', undobuffersize=1000, visible=True)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  begin_fill(self)
     |      Called just before drawing a shape to be filled.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("black", "red")
     |      >>> turtle.begin_fill()
     |      >>> turtle.circle(60)
     |      >>> turtle.end_fill()
     |  
     |  begin_poly(self)
     |      Start recording the vertices of a polygon.
     |      
     |      No argument.
     |      
     |      Start recording the vertices of a polygon. Current turtle position
     |      is first point of polygon.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.begin_poly()
     |  
     |  clear(self)
     |      Delete the turtle's drawings from the screen. Do not move turtle.
     |      
     |      No arguments.
     |      
     |      Delete the turtle's drawings from the screen. Do not move turtle.
     |      State and position of the turtle as well as drawings of other
     |      turtles are not affected.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.clear()
     |  
     |  clearstamp(self, stampid)
     |      Delete stamp with given stampid
     |      
     |      Argument:
     |      stampid - an integer, must be return value of previous stamp() call.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("blue")
     |      >>> astamp = turtle.stamp()
     |      >>> turtle.fd(50)
     |      >>> turtle.clearstamp(astamp)
     |  
     |  clearstamps(self, n=None)
     |      Delete all or first/last n of turtle's stamps.
     |      
     |      Optional argument:
     |      n -- an integer
     |      
     |      If n is None, delete all of pen's stamps,
     |      else if n > 0 delete first n stamps
     |      else if n < 0 delete last n stamps.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> for i in range(8):
     |      ...     turtle.stamp(); turtle.fd(30)
     |      ...
     |      >>> turtle.clearstamps(2)
     |      >>> turtle.clearstamps(-2)
     |      >>> turtle.clearstamps()
     |  
     |  clone(self)
     |      Create and return a clone of the turtle.
     |      
     |      No argument.
     |      
     |      Create and return a clone of the turtle with same position, heading
     |      and turtle properties.
     |      
     |      Example (for a Turtle instance named mick):
     |      mick = Turtle()
     |      joe = mick.clone()
     |  
     |  dot(self, size=None, *color)
     |      Draw a dot with diameter size, using color.
     |      
     |      Optional arguments:
     |      size -- an integer >= 1 (if given)
     |      color -- a colorstring or a numeric color tuple
     |      
     |      Draw a circular dot with diameter size, using color.
     |      If size is not given, the maximum of pensize+4 and 2*pensize is used.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.dot()
     |      >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
     |  
     |  end_fill(self)
     |      Fill the shape drawn after the call begin_fill().
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("black", "red")
     |      >>> turtle.begin_fill()
     |      >>> turtle.circle(60)
     |      >>> turtle.end_fill()
     |  
     |  end_poly(self)
     |      Stop recording the vertices of a polygon.
     |      
     |      No argument.
     |      
     |      Stop recording the vertices of a polygon. Current turtle position is
     |      last point of polygon. This will be connected with the first point.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.end_poly()
     |  
     |  filling(self)
     |      Return fillstate (True if filling, False else).
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.begin_fill()
     |      >>> if turtle.filling():
     |      ...     turtle.pensize(5)
     |      ... else:
     |      ...     turtle.pensize(3)
     |  
     |  get_poly(self)
     |      Return the lastly recorded polygon.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> p = turtle.get_poly()
     |      >>> turtle.register_shape("myFavouriteShape", p)
     |  
     |  get_shapepoly(self)
     |      Return the current shape polygon as tuple of coordinate pairs.
     |      
     |      No argument.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("square")
     |      >>> turtle.shapetransform(4, -1, 0, 2)
     |      >>> turtle.get_shapepoly()
     |      ((50, -20), (30, 20), (-50, 20), (-30, -20))
     |  
     |  getpen = getturtle(self)
     |  
     |  getscreen(self)
     |      Return the TurtleScreen object, the turtle is drawing  on.
     |      
     |      No argument.
     |      
     |      Return the TurtleScreen object, the turtle is drawing  on.
     |      So TurtleScreen-methods can be called for that object.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> ts = turtle.getscreen()
     |      >>> ts
     |      <turtle.TurtleScreen object at 0x0106B770>
     |      >>> ts.bgcolor("pink")
     |  
     |  getturtle(self)
     |      Return the Turtleobject itself.
     |      
     |      No argument.
     |      
     |      Only reasonable use: as a function to return the 'anonymous turtle':
     |      
     |      Example:
     |      >>> pet = getturtle()
     |      >>> pet.fd(50)
     |      >>> pet
     |      <turtle.Turtle object at 0x0187D810>
     |      >>> turtles()
     |      [<turtle.Turtle object at 0x0187D810>]
     |  
     |  onclick(self, fun, btn=1, add=None)
     |      Bind fun to mouse-click event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun --  a function with two arguments, to which will be assigned
     |              the coordinates of the clicked point on the canvas.
     |      num --  number of the mouse-button defaults to 1 (left mouse button).
     |      add --  True or False. If True, new binding will be added, otherwise
     |              it will replace a former binding.
     |      
     |      Example for the anonymous turtle, i. e. the procedural way:
     |      
     |      >>> def turn(x, y):
     |      ...     left(360)
     |      ...
     |      >>> onclick(turn)  # Now clicking into the turtle will turn it.
     |      >>> onclick(None)  # event-binding will be removed
     |  
     |  ondrag(self, fun, btn=1, add=None)
     |      Bind fun to mouse-move event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun -- a function with two arguments, to which will be assigned
     |             the coordinates of the clicked point on the canvas.
     |      num -- number of the mouse-button defaults to 1 (left mouse button).
     |      
     |      Every sequence of mouse-move-events on a turtle is preceded by a
     |      mouse-click event on that turtle.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.ondrag(turtle.goto)
     |      
     |      Subsequently clicking and dragging a Turtle will move it
     |      across the screen thereby producing handdrawings (if pen is
     |      down).
     |  
     |  onrelease(self, fun, btn=1, add=None)
     |      Bind fun to mouse-button-release event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun -- a function with two arguments, to which will be assigned
     |              the coordinates of the clicked point on the canvas.
     |      num --  number of the mouse-button defaults to 1 (left mouse button).
     |      
     |      Example (for a MyTurtle instance named joe):
     |      >>> class MyTurtle(Turtle):
     |      ...     def glow(self,x,y):
     |      ...             self.fillcolor("red")
     |      ...     def unglow(self,x,y):
     |      ...             self.fillcolor("")
     |      ...
     |      >>> joe = MyTurtle()
     |      >>> joe.onclick(joe.glow)
     |      >>> joe.onrelease(joe.unglow)
     |      
     |      Clicking on joe turns fillcolor red, unclicking turns it to
     |      transparent.
     |  
     |  reset(self)
     |      Delete the turtle's drawings and restore its default values.
     |      
     |      No argument.
     |      
     |      Delete the turtle's drawings from the screen, re-center the turtle
     |      and set variables to the default values.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00,-22.00)
     |      >>> turtle.heading()
     |      100.0
     |      >>> turtle.reset()
     |      >>> turtle.position()
     |      (0.00,0.00)
     |      >>> turtle.heading()
     |      0.0
     |  
     |  settiltangle(self, angle)
     |      Rotate the turtleshape to point in the specified direction
     |      
     |      Argument: angle -- number
     |      
     |      Rotate the turtleshape to point in the direction specified by angle,
     |      regardless of its current tilt-angle. DO NOT change the turtle's
     |      heading (direction of movement).
     |      
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.settiltangle(45)
     |      >>> stamp()
     |      >>> turtle.fd(50)
     |      >>> turtle.settiltangle(-45)
     |      >>> stamp()
     |      >>> turtle.fd(50)
     |  
     |  setundobuffer(self, size)
     |      Set or disable undobuffer.
     |      
     |      Argument:
     |      size -- an integer or None
     |      
     |      If size is an integer an empty undobuffer of given size is installed.
     |      Size gives the maximum number of turtle-actions that can be undone
     |      by the undo() function.
     |      If size is None, no undobuffer is present.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.setundobuffer(42)
     |  
     |  shape(self, name=None)
     |      Set turtle shape to shape with given name / return current shapename.
     |      
     |      Optional argument:
     |      name -- a string, which is a valid shapename
     |      
     |      Set turtle shape to shape with given name or, if name is not given,
     |      return name of current shape.
     |      Shape with name must exist in the TurtleScreen's shape dictionary.
     |      Initially there are the following polygon shapes:
     |      'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'.
     |      To learn about how to deal with shapes see Screen-method register_shape.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.shape()
     |      'arrow'
     |      >>> turtle.shape("turtle")
     |      >>> turtle.shape()
     |      'turtle'
     |  
     |  shapesize(self, stretch_wid=None, stretch_len=None, outline=None)
     |      Set/return turtle's stretchfactors/outline. Set resizemode to "user".
     |      
     |      Optional arguments:
     |         stretch_wid : positive number
     |         stretch_len : positive number
     |         outline  : positive number
     |      
     |      Return or set the pen's attributes x/y-stretchfactors and/or outline.
     |      Set resizemode to "user".
     |      If and only if resizemode is set to "user", the turtle will be displayed
     |      stretched according to its stretchfactors:
     |      stretch_wid is stretchfactor perpendicular to orientation
     |      stretch_len is stretchfactor in direction of turtles orientation.
     |      outline determines the width of the shapes's outline.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.resizemode("user")
     |      >>> turtle.shapesize(5, 5, 12)
     |      >>> turtle.shapesize(outline=8)
     |  
     |  shapetransform(self, t11=None, t12=None, t21=None, t22=None)
     |      Set or return the current transformation matrix of the turtle shape.
     |      
     |      Optional arguments: t11, t12, t21, t22 -- numbers.
     |      
     |      If none of the matrix elements are given, return the transformation
     |      matrix.
     |      Otherwise set the given elements and transform the turtleshape
     |      according to the matrix consisting of first row t11, t12 and
     |      second row t21, 22.
     |      Modify stretchfactor, shearfactor and tiltangle according to the
     |      given matrix.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("square")
     |      >>> turtle.shapesize(4,2)
     |      >>> turtle.shearfactor(-0.5)
     |      >>> turtle.shapetransform()
     |      (4.0, -1.0, -0.0, 2.0)
     |  
     |  shearfactor(self, shear=None)
     |      Set or return the current shearfactor.
     |      
     |      Optional argument: shear -- number, tangent of the shear angle
     |      
     |      Shear the turtleshape according to the given shearfactor shear,
     |      which is the tangent of the shear angle. DO NOT change the
     |      turtle's heading (direction of movement).
     |      If shear is not given: return the current shearfactor, i. e. the
     |      tangent of the shear angle, by which lines parallel to the
     |      heading of the turtle are sheared.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.shearfactor(0.5)
     |      >>> turtle.shearfactor()
     |      >>> 0.5
     |  
     |  stamp(self)
     |      Stamp a copy of the turtleshape onto the canvas and return its id.
     |      
     |      No argument.
     |      
     |      Stamp a copy of the turtle shape onto the canvas at the current
     |      turtle position. Return a stamp_id for that stamp, which can be
     |      used to delete it by calling clearstamp(stamp_id).
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("blue")
     |      >>> turtle.stamp()
     |      13
     |      >>> turtle.fd(50)
     |  
     |  tilt(self, angle)
     |      Rotate the turtleshape by angle.
     |      
     |      Argument:
     |      angle - a number
     |      
     |      Rotate the turtleshape by angle from its current tilt-angle,
     |      but do NOT change the turtle's heading (direction of movement).
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.tilt(30)
     |      >>> turtle.fd(50)
     |      >>> turtle.tilt(30)
     |      >>> turtle.fd(50)
     |  
     |  tiltangle(self, angle=None)
     |      Set or return the current tilt-angle.
     |      
     |      Optional argument: angle -- number
     |      
     |      Rotate the turtleshape to point in the direction specified by angle,
     |      regardless of its current tilt-angle. DO NOT change the turtle's
     |      heading (direction of movement).
     |      If angle is not given: return the current tilt-angle, i. e. the angle
     |      between the orientation of the turtleshape and the heading of the
     |      turtle (its direction of movement).
     |      
     |      Deprecated since Python 3.1
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.tilt(45)
     |      >>> turtle.tiltangle()
     |  
     |  turtlesize = shapesize(self, stretch_wid=None, stretch_len=None, outline=None)
     |  
     |  undo(self)
     |      undo (repeatedly) the last turtle action.
     |      
     |      No argument.
     |      
     |      undo (repeatedly) the last turtle action.
     |      Number of available undo actions is determined by the size of
     |      the undobuffer.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> for i in range(4):
     |      ...     turtle.fd(50); turtle.lt(80)
     |      ...
     |      >>> for i in range(8):
     |      ...     turtle.undo()
     |      ...
     |  
     |  undobufferentries(self)
     |      Return count of entries in the undobuffer.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> while undobufferentries():
     |      ...     undo()
     |  
     |  write(self, arg, move=False, align='left', font=('Arial', 8, 'normal'))
     |      Write text at the current turtle position.
     |      
     |      Arguments:
     |      arg -- info, which is to be written to the TurtleScreen
     |      move (optional) -- True/False
     |      align (optional) -- one of the strings "left", "center" or right"
     |      font (optional) -- a triple (fontname, fontsize, fonttype)
     |      
     |      Write text - the string representation of arg - at the current
     |      turtle position according to align ("left", "center" or right")
     |      and with the given font.
     |      If move is True, the pen is moved to the bottom-right corner
     |      of the text. By default, move is False.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.write('Home = ', True, align="center")
     |      >>> turtle.write((0,0), True)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  screens = []
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from TPen:
     |  
     |  color(self, *args)
     |      Return or set the pencolor and fillcolor.
     |      
     |      Arguments:
     |      Several input formats are allowed.
     |      They use 0, 1, 2, or 3 arguments as follows:
     |      
     |      color()
     |          Return the current pencolor and the current fillcolor
     |          as a pair of color specification strings as are returned
     |          by pencolor and fillcolor.
     |      color(colorstring), color((r,g,b)), color(r,g,b)
     |          inputs as in pencolor, set both, fillcolor and pencolor,
     |          to the given value.
     |      color(colorstring1, colorstring2),
     |      color((r1,g1,b1), (r2,g2,b2))
     |          equivalent to pencolor(colorstring1) and fillcolor(colorstring2)
     |          and analogously, if the other input format is used.
     |      
     |      If turtleshape is a polygon, outline and interior of that polygon
     |      is drawn with the newly set colors.
     |      For mor info see: pencolor, fillcolor
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color('red', 'green')
     |      >>> turtle.color()
     |      ('red', 'green')
     |      >>> colormode(255)
     |      >>> color((40, 80, 120), (160, 200, 240))
     |      >>> color()
     |      ('#285078', '#a0c8f0')
     |  
     |  down = pendown(self)
     |      Pull the pen down -- drawing when moving.
     |      
     |      Aliases: pendown | pd | down
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pendown()
     |  
     |  fillcolor(self, *args)
     |      Return or set the fillcolor.
     |      
     |      Arguments:
     |      Four input formats are allowed:
     |        - fillcolor()
     |          Return the current fillcolor as color specification string,
     |          possibly in hex-number format (see example).
     |          May be used as input to another color/pencolor/fillcolor call.
     |        - fillcolor(colorstring)
     |          s is a Tk color specification string, such as "red" or "yellow"
     |        - fillcolor((r, g, b))
     |          *a tuple* of r, g, and b, which represent, an RGB color,
     |          and each of r, g, and b are in the range 0..colormode,
     |          where colormode is either 1.0 or 255
     |        - fillcolor(r, g, b)
     |          r, g, and b represent an RGB color, and each of r, g, and b
     |          are in the range 0..colormode
     |      
     |      If turtleshape is a polygon, the interior of that polygon is drawn
     |      with the newly set fillcolor.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.fillcolor('violet')
     |      >>> col = turtle.pencolor()
     |      >>> turtle.fillcolor(col)
     |      >>> turtle.fillcolor(0, .5, 0)
     |  
     |  hideturtle(self)
     |      Makes the turtle invisible.
     |      
     |      Aliases: hideturtle | ht
     |      
     |      No argument.
     |      
     |      It's a good idea to do this while you're in the
     |      middle of a complicated drawing, because hiding
     |      the turtle speeds up the drawing observably.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |  
     |  ht = hideturtle(self)
     |      Makes the turtle invisible.
     |      
     |      Aliases: hideturtle | ht
     |      
     |      No argument.
     |      
     |      It's a good idea to do this while you're in the
     |      middle of a complicated drawing, because hiding
     |      the turtle speeds up the drawing observably.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |  
     |  isdown(self)
     |      Return True if pen is down, False if it's up.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |      >>> turtle.isdown()
     |      False
     |      >>> turtle.pendown()
     |      >>> turtle.isdown()
     |      True
     |  
     |  isvisible(self)
     |      Return True if the Turtle is shown, False if it's hidden.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |      >>> print turtle.isvisible():
     |      False
     |  
     |  pd = pendown(self)
     |      Pull the pen down -- drawing when moving.
     |      
     |      Aliases: pendown | pd | down
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pendown()
     |  
     |  pen(self, pen=None, **pendict)
     |      Return or set the pen's attributes.
     |      
     |      Arguments:
     |          pen -- a dictionary with some or all of the below listed keys.
     |          **pendict -- one or more keyword-arguments with the below
     |                       listed keys as keywords.
     |      
     |      Return or set the pen's attributes in a 'pen-dictionary'
     |      with the following key/value pairs:
     |         "shown"      :   True/False
     |         "pendown"    :   True/False
     |         "pencolor"   :   color-string or color-tuple
     |         "fillcolor"  :   color-string or color-tuple
     |         "pensize"    :   positive number
     |         "speed"      :   number in range 0..10
     |         "resizemode" :   "auto" or "user" or "noresize"
     |         "stretchfactor": (positive number, positive number)
     |         "shearfactor":   number
     |         "outline"    :   positive number
     |         "tilt"       :   number
     |      
     |      This dictionary can be used as argument for a subsequent
     |      pen()-call to restore the former pen-state. Moreover one
     |      or more of these attributes can be provided as keyword-arguments.
     |      This can be used to set several pen attributes in one statement.
     |      
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
     |      >>> turtle.pen()
     |      {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
     |      'pencolor': 'red', 'pendown': True, 'fillcolor': 'black',
     |      'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
     |      >>> penstate=turtle.pen()
     |      >>> turtle.color("yellow","")
     |      >>> turtle.penup()
     |      >>> turtle.pen()
     |      {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
     |      'pencolor': 'yellow', 'pendown': False, 'fillcolor': '',
     |      'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
     |      >>> p.pen(penstate, fillcolor="green")
     |      >>> p.pen()
     |      {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
     |      'pencolor': 'red', 'pendown': True, 'fillcolor': 'green',
     |      'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
     |  
     |  pencolor(self, *args)
     |      Return or set the pencolor.
     |      
     |      Arguments:
     |      Four input formats are allowed:
     |        - pencolor()
     |          Return the current pencolor as color specification string,
     |          possibly in hex-number format (see example).
     |          May be used as input to another color/pencolor/fillcolor call.
     |        - pencolor(colorstring)
     |          s is a Tk color specification string, such as "red" or "yellow"
     |        - pencolor((r, g, b))
     |          *a tuple* of r, g, and b, which represent, an RGB color,
     |          and each of r, g, and b are in the range 0..colormode,
     |          where colormode is either 1.0 or 255
     |        - pencolor(r, g, b)
     |          r, g, and b represent an RGB color, and each of r, g, and b
     |          are in the range 0..colormode
     |      
     |      If turtleshape is a polygon, the outline of that polygon is drawn
     |      with the newly set pencolor.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pencolor('brown')
     |      >>> tup = (0.2, 0.8, 0.55)
     |      >>> turtle.pencolor(tup)
     |      >>> turtle.pencolor()
     |      '#33cc8c'
     |  
     |  pendown(self)
     |      Pull the pen down -- drawing when moving.
     |      
     |      Aliases: pendown | pd | down
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pendown()
     |  
     |  pensize(self, width=None)
     |      Set or return the line thickness.
     |      
     |      Aliases:  pensize | width
     |      
     |      Argument:
     |      width -- positive number
     |      
     |      Set the line thickness to width or return it. If resizemode is set
     |      to "auto" and turtleshape is a polygon, that polygon is drawn with
     |      the same line thickness. If no argument is given, current pensize
     |      is returned.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pensize()
     |      1
     |      >>> turtle.pensize(10)   # from here on lines of width 10 are drawn
     |  
     |  penup(self)
     |      Pull the pen up -- no drawing when moving.
     |      
     |      Aliases: penup | pu | up
     |      
     |      No argument
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |  
     |  pu = penup(self)
     |      Pull the pen up -- no drawing when moving.
     |      
     |      Aliases: penup | pu | up
     |      
     |      No argument
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |  
     |  resizemode(self, rmode=None)
     |      Set resizemode to one of the values: "auto", "user", "noresize".
     |      
     |      (Optional) Argument:
     |      rmode -- one of the strings "auto", "user", "noresize"
     |      
     |      Different resizemodes have the following effects:
     |        - "auto" adapts the appearance of the turtle
     |                 corresponding to the value of pensize.
     |        - "user" adapts the appearance of the turtle according to the
     |                 values of stretchfactor and outlinewidth (outline),
     |                 which are set by shapesize()
     |        - "noresize" no adaption of the turtle's appearance takes place.
     |      If no argument is given, return current resizemode.
     |      resizemode("user") is called by a call of shapesize with arguments.
     |      
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.resizemode("noresize")
     |      >>> turtle.resizemode()
     |      'noresize'
     |  
     |  showturtle(self)
     |      Makes the turtle visible.
     |      
     |      Aliases: showturtle | st
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |      >>> turtle.showturtle()
     |  
     |  speed(self, speed=None)
     |      Return or set the turtle's speed.
     |      
     |      Optional argument:
     |      speed -- an integer in the range 0..10 or a speedstring (see below)
     |      
     |      Set the turtle's speed to an integer value in the range 0 .. 10.
     |      If no argument is given: return current speed.
     |      
     |      If input is a number greater than 10 or smaller than 0.5,
     |      speed is set to 0.
     |      Speedstrings  are mapped to speedvalues in the following way:
     |          'fastest' :  0
     |          'fast'    :  10
     |          'normal'  :  6
     |          'slow'    :  3
     |          'slowest' :  1
     |      speeds from 1 to 10 enforce increasingly faster animation of
     |      line drawing and turtle turning.
     |      
     |      Attention:
     |      speed = 0 : *no* animation takes place. forward/back makes turtle jump
     |      and likewise left/right make the turtle turn instantly.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.speed(3)
     |  
     |  st = showturtle(self)
     |      Makes the turtle visible.
     |      
     |      Aliases: showturtle | st
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |      >>> turtle.showturtle()
     |  
     |  up = penup(self)
     |      Pull the pen up -- no drawing when moving.
     |      
     |      Aliases: penup | pu | up
     |      
     |      No argument
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |  
     |  width = pensize(self, width=None)
     |      Set or return the line thickness.
     |      
     |      Aliases:  pensize | width
     |      
     |      Argument:
     |      width -- positive number
     |      
     |      Set the line thickness to width or return it. If resizemode is set
     |      to "auto" and turtleshape is a polygon, that polygon is drawn with
     |      the same line thickness. If no argument is given, current pensize
     |      is returned.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pensize()
     |      1
     |      >>> turtle.pensize(10)   # from here on lines of width 10 are drawn
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from TPen:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from TNavigator:
     |  
     |  back(self, distance)
     |      Move the turtle backward by distance.
     |      
     |      Aliases: back | backward | bk
     |      
     |      Argument:
     |      distance -- a number
     |      
     |      Move the turtle backward by distance ,opposite to the direction the
     |      turtle is headed. Do not change the turtle's heading.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.backward(30)
     |      >>> turtle.position()
     |      (-30.00, 0.00)
     |  
     |  backward = back(self, distance)
     |      Move the turtle backward by distance.
     |      
     |      Aliases: back | backward | bk
     |      
     |      Argument:
     |      distance -- a number
     |      
     |      Move the turtle backward by distance ,opposite to the direction the
     |      turtle is headed. Do not change the turtle's heading.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.backward(30)
     |      >>> turtle.position()
     |      (-30.00, 0.00)
     |  
     |  bk = back(self, distance)
     |      Move the turtle backward by distance.
     |      
     |      Aliases: back | backward | bk
     |      
     |      Argument:
     |      distance -- a number
     |      
     |      Move the turtle backward by distance ,opposite to the direction the
     |      turtle is headed. Do not change the turtle's heading.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.backward(30)
     |      >>> turtle.position()
     |      (-30.00, 0.00)
     |  
     |  circle(self, radius, extent=None, steps=None)
     |      Draw a circle with given radius.
     |      
     |      Arguments:
     |      radius -- a number
     |      extent (optional) -- a number
     |      steps (optional) -- an integer
     |      
     |      Draw a circle with given radius. The center is radius units left
     |      of the turtle; extent - an angle - determines which part of the
     |      circle is drawn. If extent is not given, draw the entire circle.
     |      If extent is not a full circle, one endpoint of the arc is the
     |      current pen position. Draw the arc in counterclockwise direction
     |      if radius is positive, otherwise in clockwise direction. Finally
     |      the direction of the turtle is changed by the amount of extent.
     |      
     |      As the circle is approximated by an inscribed regular polygon,
     |      steps determines the number of steps to use. If not given,
     |      it will be calculated automatically. Maybe used to draw regular
     |      polygons.
     |      
     |      call: circle(radius)                  # full circle
     |      --or: circle(radius, extent)          # arc
     |      --or: circle(radius, extent, steps)
     |      --or: circle(radius, steps=6)         # 6-sided polygon
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.circle(50)
     |      >>> turtle.circle(120, 180)  # semicircle
     |  
     |  degrees(self, fullcircle=360.0)
     |      Set angle measurement units to degrees.
     |      
     |      Optional argument:
     |      fullcircle -  a number
     |      
     |      Set angle measurement units, i. e. set number
     |      of 'degrees' for a full circle. Dafault value is
     |      360 degrees.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.left(90)
     |      >>> turtle.heading()
     |      90
     |      
     |      Change angle measurement unit to grad (also known as gon,
     |      grade, or gradian and equals 1/100-th of the right angle.)
     |      >>> turtle.degrees(400.0)
     |      >>> turtle.heading()
     |      100
     |  
     |  distance(self, x, y=None)
     |      Return the distance from the turtle to (x,y) in turtle step units.
     |      
     |      Arguments:
     |      x -- a number   or  a pair/vector of numbers   or   a turtle instance
     |      y -- a number       None                            None
     |      
     |      call: distance(x, y)         # two coordinates
     |      --or: distance((x, y))       # a pair (tuple) of coordinates
     |      --or: distance(vec)          # e.g. as returned by pos()
     |      --or: distance(mypen)        # where mypen is another turtle
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (0.00, 0.00)
     |      >>> turtle.distance(30,40)
     |      50.0
     |      >>> pen = Turtle()
     |      >>> pen.forward(77)
     |      >>> turtle.distance(pen)
     |      77.0
     |  
     |  fd = forward(self, distance)
     |      Move the turtle forward by the specified distance.
     |      
     |      Aliases: forward | fd
     |      
     |      Argument:
     |      distance -- a number (integer or float)
     |      
     |      Move the turtle forward by the specified distance, in the direction
     |      the turtle is headed.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.forward(25)
     |      >>> turtle.position()
     |      (25.00,0.00)
     |      >>> turtle.forward(-75)
     |      >>> turtle.position()
     |      (-50.00,0.00)
     |  
     |  forward(self, distance)
     |      Move the turtle forward by the specified distance.
     |      
     |      Aliases: forward | fd
     |      
     |      Argument:
     |      distance -- a number (integer or float)
     |      
     |      Move the turtle forward by the specified distance, in the direction
     |      the turtle is headed.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.forward(25)
     |      >>> turtle.position()
     |      (25.00,0.00)
     |      >>> turtle.forward(-75)
     |      >>> turtle.position()
     |      (-50.00,0.00)
     |  
     |  goto(self, x, y=None)
     |      Move turtle to an absolute position.
     |      
     |      Aliases: setpos | setposition | goto:
     |      
     |      Arguments:
     |      x -- a number      or     a pair/vector of numbers
     |      y -- a number             None
     |      
     |      call: goto(x, y)         # two coordinates
     |      --or: goto((x, y))       # a pair (tuple) of coordinates
     |      --or: goto(vec)          # e.g. as returned by pos()
     |      
     |      Move turtle to an absolute position. If the pen is down,
     |      a line will be drawn. The turtle's orientation does not change.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> tp = turtle.pos()
     |      >>> tp
     |      (0.00, 0.00)
     |      >>> turtle.setpos(60,30)
     |      >>> turtle.pos()
     |      (60.00,30.00)
     |      >>> turtle.setpos((20,80))
     |      >>> turtle.pos()
     |      (20.00,80.00)
     |      >>> turtle.setpos(tp)
     |      >>> turtle.pos()
     |      (0.00,0.00)
     |  
     |  heading(self)
     |      Return the turtle's current heading.
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.left(67)
     |      >>> turtle.heading()
     |      67.0
     |  
     |  home(self)
     |      Move turtle to the origin - coordinates (0,0).
     |      
     |      No arguments.
     |      
     |      Move turtle to the origin - coordinates (0,0) and set its
     |      heading to its start-orientation (which depends on mode).
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.home()
     |  
     |  left(self, angle)
     |      Turn turtle left by angle units.
     |      
     |      Aliases: left | lt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle left by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.left(45)
     |      >>> turtle.heading()
     |      67.0
     |  
     |  lt = left(self, angle)
     |      Turn turtle left by angle units.
     |      
     |      Aliases: left | lt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle left by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.left(45)
     |      >>> turtle.heading()
     |      67.0
     |  
     |  pos(self)
     |      Return the turtle's current location (x,y), as a Vec2D-vector.
     |      
     |      Aliases: pos | position
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (0.00, 240.00)
     |  
     |  position = pos(self)
     |      Return the turtle's current location (x,y), as a Vec2D-vector.
     |      
     |      Aliases: pos | position
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (0.00, 240.00)
     |  
     |  radians(self)
     |      Set the angle measurement units to radians.
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      90
     |      >>> turtle.radians()
     |      >>> turtle.heading()
     |      1.5707963267948966
     |  
     |  right(self, angle)
     |      Turn turtle right by angle units.
     |      
     |      Aliases: right | rt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle right by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.right(45)
     |      >>> turtle.heading()
     |      337.0
     |  
     |  rt = right(self, angle)
     |      Turn turtle right by angle units.
     |      
     |      Aliases: right | rt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle right by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.right(45)
     |      >>> turtle.heading()
     |      337.0
     |  
     |  seth = setheading(self, to_angle)
     |      Set the orientation of the turtle to to_angle.
     |      
     |      Aliases:  setheading | seth
     |      
     |      Argument:
     |      to_angle -- a number (integer or float)
     |      
     |      Set the orientation of the turtle to to_angle.
     |      Here are some common directions in degrees:
     |      
     |       standard - mode:          logo-mode:
     |      -------------------|--------------------
     |         0 - east                0 - north
     |        90 - north              90 - east
     |       180 - west              180 - south
     |       270 - south             270 - west
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.setheading(90)
     |      >>> turtle.heading()
     |      90
     |  
     |  setheading(self, to_angle)
     |      Set the orientation of the turtle to to_angle.
     |      
     |      Aliases:  setheading | seth
     |      
     |      Argument:
     |      to_angle -- a number (integer or float)
     |      
     |      Set the orientation of the turtle to to_angle.
     |      Here are some common directions in degrees:
     |      
     |       standard - mode:          logo-mode:
     |      -------------------|--------------------
     |         0 - east                0 - north
     |        90 - north              90 - east
     |       180 - west              180 - south
     |       270 - south             270 - west
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.setheading(90)
     |      >>> turtle.heading()
     |      90
     |  
     |  setpos = goto(self, x, y=None)
     |      Move turtle to an absolute position.
     |      
     |      Aliases: setpos | setposition | goto:
     |      
     |      Arguments:
     |      x -- a number      or     a pair/vector of numbers
     |      y -- a number             None
     |      
     |      call: goto(x, y)         # two coordinates
     |      --or: goto((x, y))       # a pair (tuple) of coordinates
     |      --or: goto(vec)          # e.g. as returned by pos()
     |      
     |      Move turtle to an absolute position. If the pen is down,
     |      a line will be drawn. The turtle's orientation does not change.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> tp = turtle.pos()
     |      >>> tp
     |      (0.00, 0.00)
     |      >>> turtle.setpos(60,30)
     |      >>> turtle.pos()
     |      (60.00,30.00)
     |      >>> turtle.setpos((20,80))
     |      >>> turtle.pos()
     |      (20.00,80.00)
     |      >>> turtle.setpos(tp)
     |      >>> turtle.pos()
     |      (0.00,0.00)
     |  
     |  setposition = goto(self, x, y=None)
     |      Move turtle to an absolute position.
     |      
     |      Aliases: setpos | setposition | goto:
     |      
     |      Arguments:
     |      x -- a number      or     a pair/vector of numbers
     |      y -- a number             None
     |      
     |      call: goto(x, y)         # two coordinates
     |      --or: goto((x, y))       # a pair (tuple) of coordinates
     |      --or: goto(vec)          # e.g. as returned by pos()
     |      
     |      Move turtle to an absolute position. If the pen is down,
     |      a line will be drawn. The turtle's orientation does not change.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> tp = turtle.pos()
     |      >>> tp
     |      (0.00, 0.00)
     |      >>> turtle.setpos(60,30)
     |      >>> turtle.pos()
     |      (60.00,30.00)
     |      >>> turtle.setpos((20,80))
     |      >>> turtle.pos()
     |      (20.00,80.00)
     |      >>> turtle.setpos(tp)
     |      >>> turtle.pos()
     |      (0.00,0.00)
     |  
     |  setx(self, x)
     |      Set the turtle's first coordinate to x
     |      
     |      Argument:
     |      x -- a number (integer or float)
     |      
     |      Set the turtle's first coordinate to x, leave second coordinate
     |      unchanged.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 240.00)
     |      >>> turtle.setx(10)
     |      >>> turtle.position()
     |      (10.00, 240.00)
     |  
     |  sety(self, y)
     |      Set the turtle's second coordinate to y
     |      
     |      Argument:
     |      y -- a number (integer or float)
     |      
     |      Set the turtle's first coordinate to x, second coordinate remains
     |      unchanged.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 40.00)
     |      >>> turtle.sety(-10)
     |      >>> turtle.position()
     |      (0.00, -10.00)
     |  
     |  towards(self, x, y=None)
     |      Return the angle of the line from the turtle's position to (x, y).
     |      
     |      Arguments:
     |      x -- a number   or  a pair/vector of numbers   or   a turtle instance
     |      y -- a number       None                            None
     |      
     |      call: distance(x, y)         # two coordinates
     |      --or: distance((x, y))       # a pair (tuple) of coordinates
     |      --or: distance(vec)          # e.g. as returned by pos()
     |      --or: distance(mypen)        # where mypen is another turtle
     |      
     |      Return the angle, between the line from turtle-position to position
     |      specified by x, y and the turtle's start orientation. (Depends on
     |      modes - "standard" or "logo")
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (10.00, 10.00)
     |      >>> turtle.towards(0,0)
     |      225.0
     |  
     |  xcor(self)
     |      Return the turtle's x coordinate.
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> reset()
     |      >>> turtle.left(60)
     |      >>> turtle.forward(100)
     |      >>> print turtle.xcor()
     |      50.0
     |  
     |  ycor(self)
     |      Return the turtle's y coordinate
     |      ---
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> reset()
     |      >>> turtle.left(60)
     |      >>> turtle.forward(100)
     |      >>> print turtle.ycor()
     |      86.6025403784
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from TNavigator:
     |  
     |  DEFAULT_ANGLEOFFSET = 0
     |  
     |  DEFAULT_ANGLEORIENT = 1
     |  
     |  DEFAULT_MODE = 'standard'
     |  
     |  START_ORIENTATION = {'logo': (0.00,1.00), 'standard': (1.00,0.00), 'wo...
    
    class RawTurtle(TPen, TNavigator)
     |  Animation part of the RawTurtle.
     |  Puts RawTurtle upon a TurtleScreen and provides tools for
     |  its animation.
     |  
     |  Method resolution order:
     |      RawTurtle
     |      TPen
     |      TNavigator
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, canvas=None, shape='classic', undobuffersize=1000, visible=True)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  begin_fill(self)
     |      Called just before drawing a shape to be filled.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("black", "red")
     |      >>> turtle.begin_fill()
     |      >>> turtle.circle(60)
     |      >>> turtle.end_fill()
     |  
     |  begin_poly(self)
     |      Start recording the vertices of a polygon.
     |      
     |      No argument.
     |      
     |      Start recording the vertices of a polygon. Current turtle position
     |      is first point of polygon.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.begin_poly()
     |  
     |  clear(self)
     |      Delete the turtle's drawings from the screen. Do not move turtle.
     |      
     |      No arguments.
     |      
     |      Delete the turtle's drawings from the screen. Do not move turtle.
     |      State and position of the turtle as well as drawings of other
     |      turtles are not affected.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.clear()
     |  
     |  clearstamp(self, stampid)
     |      Delete stamp with given stampid
     |      
     |      Argument:
     |      stampid - an integer, must be return value of previous stamp() call.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("blue")
     |      >>> astamp = turtle.stamp()
     |      >>> turtle.fd(50)
     |      >>> turtle.clearstamp(astamp)
     |  
     |  clearstamps(self, n=None)
     |      Delete all or first/last n of turtle's stamps.
     |      
     |      Optional argument:
     |      n -- an integer
     |      
     |      If n is None, delete all of pen's stamps,
     |      else if n > 0 delete first n stamps
     |      else if n < 0 delete last n stamps.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> for i in range(8):
     |      ...     turtle.stamp(); turtle.fd(30)
     |      ...
     |      >>> turtle.clearstamps(2)
     |      >>> turtle.clearstamps(-2)
     |      >>> turtle.clearstamps()
     |  
     |  clone(self)
     |      Create and return a clone of the turtle.
     |      
     |      No argument.
     |      
     |      Create and return a clone of the turtle with same position, heading
     |      and turtle properties.
     |      
     |      Example (for a Turtle instance named mick):
     |      mick = Turtle()
     |      joe = mick.clone()
     |  
     |  dot(self, size=None, *color)
     |      Draw a dot with diameter size, using color.
     |      
     |      Optional arguments:
     |      size -- an integer >= 1 (if given)
     |      color -- a colorstring or a numeric color tuple
     |      
     |      Draw a circular dot with diameter size, using color.
     |      If size is not given, the maximum of pensize+4 and 2*pensize is used.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.dot()
     |      >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
     |  
     |  end_fill(self)
     |      Fill the shape drawn after the call begin_fill().
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("black", "red")
     |      >>> turtle.begin_fill()
     |      >>> turtle.circle(60)
     |      >>> turtle.end_fill()
     |  
     |  end_poly(self)
     |      Stop recording the vertices of a polygon.
     |      
     |      No argument.
     |      
     |      Stop recording the vertices of a polygon. Current turtle position is
     |      last point of polygon. This will be connected with the first point.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.end_poly()
     |  
     |  filling(self)
     |      Return fillstate (True if filling, False else).
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.begin_fill()
     |      >>> if turtle.filling():
     |      ...     turtle.pensize(5)
     |      ... else:
     |      ...     turtle.pensize(3)
     |  
     |  get_poly(self)
     |      Return the lastly recorded polygon.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> p = turtle.get_poly()
     |      >>> turtle.register_shape("myFavouriteShape", p)
     |  
     |  get_shapepoly(self)
     |      Return the current shape polygon as tuple of coordinate pairs.
     |      
     |      No argument.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("square")
     |      >>> turtle.shapetransform(4, -1, 0, 2)
     |      >>> turtle.get_shapepoly()
     |      ((50, -20), (30, 20), (-50, 20), (-30, -20))
     |  
     |  getpen = getturtle(self)
     |  
     |  getscreen(self)
     |      Return the TurtleScreen object, the turtle is drawing  on.
     |      
     |      No argument.
     |      
     |      Return the TurtleScreen object, the turtle is drawing  on.
     |      So TurtleScreen-methods can be called for that object.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> ts = turtle.getscreen()
     |      >>> ts
     |      <turtle.TurtleScreen object at 0x0106B770>
     |      >>> ts.bgcolor("pink")
     |  
     |  getturtle(self)
     |      Return the Turtleobject itself.
     |      
     |      No argument.
     |      
     |      Only reasonable use: as a function to return the 'anonymous turtle':
     |      
     |      Example:
     |      >>> pet = getturtle()
     |      >>> pet.fd(50)
     |      >>> pet
     |      <turtle.Turtle object at 0x0187D810>
     |      >>> turtles()
     |      [<turtle.Turtle object at 0x0187D810>]
     |  
     |  onclick(self, fun, btn=1, add=None)
     |      Bind fun to mouse-click event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun --  a function with two arguments, to which will be assigned
     |              the coordinates of the clicked point on the canvas.
     |      num --  number of the mouse-button defaults to 1 (left mouse button).
     |      add --  True or False. If True, new binding will be added, otherwise
     |              it will replace a former binding.
     |      
     |      Example for the anonymous turtle, i. e. the procedural way:
     |      
     |      >>> def turn(x, y):
     |      ...     left(360)
     |      ...
     |      >>> onclick(turn)  # Now clicking into the turtle will turn it.
     |      >>> onclick(None)  # event-binding will be removed
     |  
     |  ondrag(self, fun, btn=1, add=None)
     |      Bind fun to mouse-move event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun -- a function with two arguments, to which will be assigned
     |             the coordinates of the clicked point on the canvas.
     |      num -- number of the mouse-button defaults to 1 (left mouse button).
     |      
     |      Every sequence of mouse-move-events on a turtle is preceded by a
     |      mouse-click event on that turtle.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.ondrag(turtle.goto)
     |      
     |      Subsequently clicking and dragging a Turtle will move it
     |      across the screen thereby producing handdrawings (if pen is
     |      down).
     |  
     |  onrelease(self, fun, btn=1, add=None)
     |      Bind fun to mouse-button-release event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun -- a function with two arguments, to which will be assigned
     |              the coordinates of the clicked point on the canvas.
     |      num --  number of the mouse-button defaults to 1 (left mouse button).
     |      
     |      Example (for a MyTurtle instance named joe):
     |      >>> class MyTurtle(Turtle):
     |      ...     def glow(self,x,y):
     |      ...             self.fillcolor("red")
     |      ...     def unglow(self,x,y):
     |      ...             self.fillcolor("")
     |      ...
     |      >>> joe = MyTurtle()
     |      >>> joe.onclick(joe.glow)
     |      >>> joe.onrelease(joe.unglow)
     |      
     |      Clicking on joe turns fillcolor red, unclicking turns it to
     |      transparent.
     |  
     |  reset(self)
     |      Delete the turtle's drawings and restore its default values.
     |      
     |      No argument.
     |      
     |      Delete the turtle's drawings from the screen, re-center the turtle
     |      and set variables to the default values.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00,-22.00)
     |      >>> turtle.heading()
     |      100.0
     |      >>> turtle.reset()
     |      >>> turtle.position()
     |      (0.00,0.00)
     |      >>> turtle.heading()
     |      0.0
     |  
     |  settiltangle(self, angle)
     |      Rotate the turtleshape to point in the specified direction
     |      
     |      Argument: angle -- number
     |      
     |      Rotate the turtleshape to point in the direction specified by angle,
     |      regardless of its current tilt-angle. DO NOT change the turtle's
     |      heading (direction of movement).
     |      
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.settiltangle(45)
     |      >>> stamp()
     |      >>> turtle.fd(50)
     |      >>> turtle.settiltangle(-45)
     |      >>> stamp()
     |      >>> turtle.fd(50)
     |  
     |  setundobuffer(self, size)
     |      Set or disable undobuffer.
     |      
     |      Argument:
     |      size -- an integer or None
     |      
     |      If size is an integer an empty undobuffer of given size is installed.
     |      Size gives the maximum number of turtle-actions that can be undone
     |      by the undo() function.
     |      If size is None, no undobuffer is present.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.setundobuffer(42)
     |  
     |  shape(self, name=None)
     |      Set turtle shape to shape with given name / return current shapename.
     |      
     |      Optional argument:
     |      name -- a string, which is a valid shapename
     |      
     |      Set turtle shape to shape with given name or, if name is not given,
     |      return name of current shape.
     |      Shape with name must exist in the TurtleScreen's shape dictionary.
     |      Initially there are the following polygon shapes:
     |      'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'.
     |      To learn about how to deal with shapes see Screen-method register_shape.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.shape()
     |      'arrow'
     |      >>> turtle.shape("turtle")
     |      >>> turtle.shape()
     |      'turtle'
     |  
     |  shapesize(self, stretch_wid=None, stretch_len=None, outline=None)
     |      Set/return turtle's stretchfactors/outline. Set resizemode to "user".
     |      
     |      Optional arguments:
     |         stretch_wid : positive number
     |         stretch_len : positive number
     |         outline  : positive number
     |      
     |      Return or set the pen's attributes x/y-stretchfactors and/or outline.
     |      Set resizemode to "user".
     |      If and only if resizemode is set to "user", the turtle will be displayed
     |      stretched according to its stretchfactors:
     |      stretch_wid is stretchfactor perpendicular to orientation
     |      stretch_len is stretchfactor in direction of turtles orientation.
     |      outline determines the width of the shapes's outline.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.resizemode("user")
     |      >>> turtle.shapesize(5, 5, 12)
     |      >>> turtle.shapesize(outline=8)
     |  
     |  shapetransform(self, t11=None, t12=None, t21=None, t22=None)
     |      Set or return the current transformation matrix of the turtle shape.
     |      
     |      Optional arguments: t11, t12, t21, t22 -- numbers.
     |      
     |      If none of the matrix elements are given, return the transformation
     |      matrix.
     |      Otherwise set the given elements and transform the turtleshape
     |      according to the matrix consisting of first row t11, t12 and
     |      second row t21, 22.
     |      Modify stretchfactor, shearfactor and tiltangle according to the
     |      given matrix.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("square")
     |      >>> turtle.shapesize(4,2)
     |      >>> turtle.shearfactor(-0.5)
     |      >>> turtle.shapetransform()
     |      (4.0, -1.0, -0.0, 2.0)
     |  
     |  shearfactor(self, shear=None)
     |      Set or return the current shearfactor.
     |      
     |      Optional argument: shear -- number, tangent of the shear angle
     |      
     |      Shear the turtleshape according to the given shearfactor shear,
     |      which is the tangent of the shear angle. DO NOT change the
     |      turtle's heading (direction of movement).
     |      If shear is not given: return the current shearfactor, i. e. the
     |      tangent of the shear angle, by which lines parallel to the
     |      heading of the turtle are sheared.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.shearfactor(0.5)
     |      >>> turtle.shearfactor()
     |      >>> 0.5
     |  
     |  stamp(self)
     |      Stamp a copy of the turtleshape onto the canvas and return its id.
     |      
     |      No argument.
     |      
     |      Stamp a copy of the turtle shape onto the canvas at the current
     |      turtle position. Return a stamp_id for that stamp, which can be
     |      used to delete it by calling clearstamp(stamp_id).
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("blue")
     |      >>> turtle.stamp()
     |      13
     |      >>> turtle.fd(50)
     |  
     |  tilt(self, angle)
     |      Rotate the turtleshape by angle.
     |      
     |      Argument:
     |      angle - a number
     |      
     |      Rotate the turtleshape by angle from its current tilt-angle,
     |      but do NOT change the turtle's heading (direction of movement).
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.tilt(30)
     |      >>> turtle.fd(50)
     |      >>> turtle.tilt(30)
     |      >>> turtle.fd(50)
     |  
     |  tiltangle(self, angle=None)
     |      Set or return the current tilt-angle.
     |      
     |      Optional argument: angle -- number
     |      
     |      Rotate the turtleshape to point in the direction specified by angle,
     |      regardless of its current tilt-angle. DO NOT change the turtle's
     |      heading (direction of movement).
     |      If angle is not given: return the current tilt-angle, i. e. the angle
     |      between the orientation of the turtleshape and the heading of the
     |      turtle (its direction of movement).
     |      
     |      Deprecated since Python 3.1
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("circle")
     |      >>> turtle.shapesize(5,2)
     |      >>> turtle.tilt(45)
     |      >>> turtle.tiltangle()
     |  
     |  turtlesize = shapesize(self, stretch_wid=None, stretch_len=None, outline=None)
     |  
     |  undo(self)
     |      undo (repeatedly) the last turtle action.
     |      
     |      No argument.
     |      
     |      undo (repeatedly) the last turtle action.
     |      Number of available undo actions is determined by the size of
     |      the undobuffer.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> for i in range(4):
     |      ...     turtle.fd(50); turtle.lt(80)
     |      ...
     |      >>> for i in range(8):
     |      ...     turtle.undo()
     |      ...
     |  
     |  undobufferentries(self)
     |      Return count of entries in the undobuffer.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> while undobufferentries():
     |      ...     undo()
     |  
     |  write(self, arg, move=False, align='left', font=('Arial', 8, 'normal'))
     |      Write text at the current turtle position.
     |      
     |      Arguments:
     |      arg -- info, which is to be written to the TurtleScreen
     |      move (optional) -- True/False
     |      align (optional) -- one of the strings "left", "center" or right"
     |      font (optional) -- a triple (fontname, fontsize, fonttype)
     |      
     |      Write text - the string representation of arg - at the current
     |      turtle position according to align ("left", "center" or right")
     |      and with the given font.
     |      If move is True, the pen is moved to the bottom-right corner
     |      of the text. By default, move is False.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.write('Home = ', True, align="center")
     |      >>> turtle.write((0,0), True)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  screens = []
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from TPen:
     |  
     |  color(self, *args)
     |      Return or set the pencolor and fillcolor.
     |      
     |      Arguments:
     |      Several input formats are allowed.
     |      They use 0, 1, 2, or 3 arguments as follows:
     |      
     |      color()
     |          Return the current pencolor and the current fillcolor
     |          as a pair of color specification strings as are returned
     |          by pencolor and fillcolor.
     |      color(colorstring), color((r,g,b)), color(r,g,b)
     |          inputs as in pencolor, set both, fillcolor and pencolor,
     |          to the given value.
     |      color(colorstring1, colorstring2),
     |      color((r1,g1,b1), (r2,g2,b2))
     |          equivalent to pencolor(colorstring1) and fillcolor(colorstring2)
     |          and analogously, if the other input format is used.
     |      
     |      If turtleshape is a polygon, outline and interior of that polygon
     |      is drawn with the newly set colors.
     |      For mor info see: pencolor, fillcolor
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color('red', 'green')
     |      >>> turtle.color()
     |      ('red', 'green')
     |      >>> colormode(255)
     |      >>> color((40, 80, 120), (160, 200, 240))
     |      >>> color()
     |      ('#285078', '#a0c8f0')
     |  
     |  down = pendown(self)
     |      Pull the pen down -- drawing when moving.
     |      
     |      Aliases: pendown | pd | down
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pendown()
     |  
     |  fillcolor(self, *args)
     |      Return or set the fillcolor.
     |      
     |      Arguments:
     |      Four input formats are allowed:
     |        - fillcolor()
     |          Return the current fillcolor as color specification string,
     |          possibly in hex-number format (see example).
     |          May be used as input to another color/pencolor/fillcolor call.
     |        - fillcolor(colorstring)
     |          s is a Tk color specification string, such as "red" or "yellow"
     |        - fillcolor((r, g, b))
     |          *a tuple* of r, g, and b, which represent, an RGB color,
     |          and each of r, g, and b are in the range 0..colormode,
     |          where colormode is either 1.0 or 255
     |        - fillcolor(r, g, b)
     |          r, g, and b represent an RGB color, and each of r, g, and b
     |          are in the range 0..colormode
     |      
     |      If turtleshape is a polygon, the interior of that polygon is drawn
     |      with the newly set fillcolor.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.fillcolor('violet')
     |      >>> col = turtle.pencolor()
     |      >>> turtle.fillcolor(col)
     |      >>> turtle.fillcolor(0, .5, 0)
     |  
     |  hideturtle(self)
     |      Makes the turtle invisible.
     |      
     |      Aliases: hideturtle | ht
     |      
     |      No argument.
     |      
     |      It's a good idea to do this while you're in the
     |      middle of a complicated drawing, because hiding
     |      the turtle speeds up the drawing observably.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |  
     |  ht = hideturtle(self)
     |      Makes the turtle invisible.
     |      
     |      Aliases: hideturtle | ht
     |      
     |      No argument.
     |      
     |      It's a good idea to do this while you're in the
     |      middle of a complicated drawing, because hiding
     |      the turtle speeds up the drawing observably.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |  
     |  isdown(self)
     |      Return True if pen is down, False if it's up.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |      >>> turtle.isdown()
     |      False
     |      >>> turtle.pendown()
     |      >>> turtle.isdown()
     |      True
     |  
     |  isvisible(self)
     |      Return True if the Turtle is shown, False if it's hidden.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |      >>> print turtle.isvisible():
     |      False
     |  
     |  pd = pendown(self)
     |      Pull the pen down -- drawing when moving.
     |      
     |      Aliases: pendown | pd | down
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pendown()
     |  
     |  pen(self, pen=None, **pendict)
     |      Return or set the pen's attributes.
     |      
     |      Arguments:
     |          pen -- a dictionary with some or all of the below listed keys.
     |          **pendict -- one or more keyword-arguments with the below
     |                       listed keys as keywords.
     |      
     |      Return or set the pen's attributes in a 'pen-dictionary'
     |      with the following key/value pairs:
     |         "shown"      :   True/False
     |         "pendown"    :   True/False
     |         "pencolor"   :   color-string or color-tuple
     |         "fillcolor"  :   color-string or color-tuple
     |         "pensize"    :   positive number
     |         "speed"      :   number in range 0..10
     |         "resizemode" :   "auto" or "user" or "noresize"
     |         "stretchfactor": (positive number, positive number)
     |         "shearfactor":   number
     |         "outline"    :   positive number
     |         "tilt"       :   number
     |      
     |      This dictionary can be used as argument for a subsequent
     |      pen()-call to restore the former pen-state. Moreover one
     |      or more of these attributes can be provided as keyword-arguments.
     |      This can be used to set several pen attributes in one statement.
     |      
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
     |      >>> turtle.pen()
     |      {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
     |      'pencolor': 'red', 'pendown': True, 'fillcolor': 'black',
     |      'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
     |      >>> penstate=turtle.pen()
     |      >>> turtle.color("yellow","")
     |      >>> turtle.penup()
     |      >>> turtle.pen()
     |      {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
     |      'pencolor': 'yellow', 'pendown': False, 'fillcolor': '',
     |      'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
     |      >>> p.pen(penstate, fillcolor="green")
     |      >>> p.pen()
     |      {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
     |      'pencolor': 'red', 'pendown': True, 'fillcolor': 'green',
     |      'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
     |  
     |  pencolor(self, *args)
     |      Return or set the pencolor.
     |      
     |      Arguments:
     |      Four input formats are allowed:
     |        - pencolor()
     |          Return the current pencolor as color specification string,
     |          possibly in hex-number format (see example).
     |          May be used as input to another color/pencolor/fillcolor call.
     |        - pencolor(colorstring)
     |          s is a Tk color specification string, such as "red" or "yellow"
     |        - pencolor((r, g, b))
     |          *a tuple* of r, g, and b, which represent, an RGB color,
     |          and each of r, g, and b are in the range 0..colormode,
     |          where colormode is either 1.0 or 255
     |        - pencolor(r, g, b)
     |          r, g, and b represent an RGB color, and each of r, g, and b
     |          are in the range 0..colormode
     |      
     |      If turtleshape is a polygon, the outline of that polygon is drawn
     |      with the newly set pencolor.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pencolor('brown')
     |      >>> tup = (0.2, 0.8, 0.55)
     |      >>> turtle.pencolor(tup)
     |      >>> turtle.pencolor()
     |      '#33cc8c'
     |  
     |  pendown(self)
     |      Pull the pen down -- drawing when moving.
     |      
     |      Aliases: pendown | pd | down
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pendown()
     |  
     |  pensize(self, width=None)
     |      Set or return the line thickness.
     |      
     |      Aliases:  pensize | width
     |      
     |      Argument:
     |      width -- positive number
     |      
     |      Set the line thickness to width or return it. If resizemode is set
     |      to "auto" and turtleshape is a polygon, that polygon is drawn with
     |      the same line thickness. If no argument is given, current pensize
     |      is returned.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pensize()
     |      1
     |      >>> turtle.pensize(10)   # from here on lines of width 10 are drawn
     |  
     |  penup(self)
     |      Pull the pen up -- no drawing when moving.
     |      
     |      Aliases: penup | pu | up
     |      
     |      No argument
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |  
     |  pu = penup(self)
     |      Pull the pen up -- no drawing when moving.
     |      
     |      Aliases: penup | pu | up
     |      
     |      No argument
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |  
     |  resizemode(self, rmode=None)
     |      Set resizemode to one of the values: "auto", "user", "noresize".
     |      
     |      (Optional) Argument:
     |      rmode -- one of the strings "auto", "user", "noresize"
     |      
     |      Different resizemodes have the following effects:
     |        - "auto" adapts the appearance of the turtle
     |                 corresponding to the value of pensize.
     |        - "user" adapts the appearance of the turtle according to the
     |                 values of stretchfactor and outlinewidth (outline),
     |                 which are set by shapesize()
     |        - "noresize" no adaption of the turtle's appearance takes place.
     |      If no argument is given, return current resizemode.
     |      resizemode("user") is called by a call of shapesize with arguments.
     |      
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.resizemode("noresize")
     |      >>> turtle.resizemode()
     |      'noresize'
     |  
     |  showturtle(self)
     |      Makes the turtle visible.
     |      
     |      Aliases: showturtle | st
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |      >>> turtle.showturtle()
     |  
     |  speed(self, speed=None)
     |      Return or set the turtle's speed.
     |      
     |      Optional argument:
     |      speed -- an integer in the range 0..10 or a speedstring (see below)
     |      
     |      Set the turtle's speed to an integer value in the range 0 .. 10.
     |      If no argument is given: return current speed.
     |      
     |      If input is a number greater than 10 or smaller than 0.5,
     |      speed is set to 0.
     |      Speedstrings  are mapped to speedvalues in the following way:
     |          'fastest' :  0
     |          'fast'    :  10
     |          'normal'  :  6
     |          'slow'    :  3
     |          'slowest' :  1
     |      speeds from 1 to 10 enforce increasingly faster animation of
     |      line drawing and turtle turning.
     |      
     |      Attention:
     |      speed = 0 : *no* animation takes place. forward/back makes turtle jump
     |      and likewise left/right make the turtle turn instantly.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.speed(3)
     |  
     |  st = showturtle(self)
     |      Makes the turtle visible.
     |      
     |      Aliases: showturtle | st
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.hideturtle()
     |      >>> turtle.showturtle()
     |  
     |  up = penup(self)
     |      Pull the pen up -- no drawing when moving.
     |      
     |      Aliases: penup | pu | up
     |      
     |      No argument
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.penup()
     |  
     |  width = pensize(self, width=None)
     |      Set or return the line thickness.
     |      
     |      Aliases:  pensize | width
     |      
     |      Argument:
     |      width -- positive number
     |      
     |      Set the line thickness to width or return it. If resizemode is set
     |      to "auto" and turtleshape is a polygon, that polygon is drawn with
     |      the same line thickness. If no argument is given, current pensize
     |      is returned.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pensize()
     |      1
     |      >>> turtle.pensize(10)   # from here on lines of width 10 are drawn
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from TPen:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from TNavigator:
     |  
     |  back(self, distance)
     |      Move the turtle backward by distance.
     |      
     |      Aliases: back | backward | bk
     |      
     |      Argument:
     |      distance -- a number
     |      
     |      Move the turtle backward by distance ,opposite to the direction the
     |      turtle is headed. Do not change the turtle's heading.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.backward(30)
     |      >>> turtle.position()
     |      (-30.00, 0.00)
     |  
     |  backward = back(self, distance)
     |      Move the turtle backward by distance.
     |      
     |      Aliases: back | backward | bk
     |      
     |      Argument:
     |      distance -- a number
     |      
     |      Move the turtle backward by distance ,opposite to the direction the
     |      turtle is headed. Do not change the turtle's heading.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.backward(30)
     |      >>> turtle.position()
     |      (-30.00, 0.00)
     |  
     |  bk = back(self, distance)
     |      Move the turtle backward by distance.
     |      
     |      Aliases: back | backward | bk
     |      
     |      Argument:
     |      distance -- a number
     |      
     |      Move the turtle backward by distance ,opposite to the direction the
     |      turtle is headed. Do not change the turtle's heading.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.backward(30)
     |      >>> turtle.position()
     |      (-30.00, 0.00)
     |  
     |  circle(self, radius, extent=None, steps=None)
     |      Draw a circle with given radius.
     |      
     |      Arguments:
     |      radius -- a number
     |      extent (optional) -- a number
     |      steps (optional) -- an integer
     |      
     |      Draw a circle with given radius. The center is radius units left
     |      of the turtle; extent - an angle - determines which part of the
     |      circle is drawn. If extent is not given, draw the entire circle.
     |      If extent is not a full circle, one endpoint of the arc is the
     |      current pen position. Draw the arc in counterclockwise direction
     |      if radius is positive, otherwise in clockwise direction. Finally
     |      the direction of the turtle is changed by the amount of extent.
     |      
     |      As the circle is approximated by an inscribed regular polygon,
     |      steps determines the number of steps to use. If not given,
     |      it will be calculated automatically. Maybe used to draw regular
     |      polygons.
     |      
     |      call: circle(radius)                  # full circle
     |      --or: circle(radius, extent)          # arc
     |      --or: circle(radius, extent, steps)
     |      --or: circle(radius, steps=6)         # 6-sided polygon
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.circle(50)
     |      >>> turtle.circle(120, 180)  # semicircle
     |  
     |  degrees(self, fullcircle=360.0)
     |      Set angle measurement units to degrees.
     |      
     |      Optional argument:
     |      fullcircle -  a number
     |      
     |      Set angle measurement units, i. e. set number
     |      of 'degrees' for a full circle. Dafault value is
     |      360 degrees.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.left(90)
     |      >>> turtle.heading()
     |      90
     |      
     |      Change angle measurement unit to grad (also known as gon,
     |      grade, or gradian and equals 1/100-th of the right angle.)
     |      >>> turtle.degrees(400.0)
     |      >>> turtle.heading()
     |      100
     |  
     |  distance(self, x, y=None)
     |      Return the distance from the turtle to (x,y) in turtle step units.
     |      
     |      Arguments:
     |      x -- a number   or  a pair/vector of numbers   or   a turtle instance
     |      y -- a number       None                            None
     |      
     |      call: distance(x, y)         # two coordinates
     |      --or: distance((x, y))       # a pair (tuple) of coordinates
     |      --or: distance(vec)          # e.g. as returned by pos()
     |      --or: distance(mypen)        # where mypen is another turtle
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (0.00, 0.00)
     |      >>> turtle.distance(30,40)
     |      50.0
     |      >>> pen = Turtle()
     |      >>> pen.forward(77)
     |      >>> turtle.distance(pen)
     |      77.0
     |  
     |  fd = forward(self, distance)
     |      Move the turtle forward by the specified distance.
     |      
     |      Aliases: forward | fd
     |      
     |      Argument:
     |      distance -- a number (integer or float)
     |      
     |      Move the turtle forward by the specified distance, in the direction
     |      the turtle is headed.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.forward(25)
     |      >>> turtle.position()
     |      (25.00,0.00)
     |      >>> turtle.forward(-75)
     |      >>> turtle.position()
     |      (-50.00,0.00)
     |  
     |  forward(self, distance)
     |      Move the turtle forward by the specified distance.
     |      
     |      Aliases: forward | fd
     |      
     |      Argument:
     |      distance -- a number (integer or float)
     |      
     |      Move the turtle forward by the specified distance, in the direction
     |      the turtle is headed.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 0.00)
     |      >>> turtle.forward(25)
     |      >>> turtle.position()
     |      (25.00,0.00)
     |      >>> turtle.forward(-75)
     |      >>> turtle.position()
     |      (-50.00,0.00)
     |  
     |  goto(self, x, y=None)
     |      Move turtle to an absolute position.
     |      
     |      Aliases: setpos | setposition | goto:
     |      
     |      Arguments:
     |      x -- a number      or     a pair/vector of numbers
     |      y -- a number             None
     |      
     |      call: goto(x, y)         # two coordinates
     |      --or: goto((x, y))       # a pair (tuple) of coordinates
     |      --or: goto(vec)          # e.g. as returned by pos()
     |      
     |      Move turtle to an absolute position. If the pen is down,
     |      a line will be drawn. The turtle's orientation does not change.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> tp = turtle.pos()
     |      >>> tp
     |      (0.00, 0.00)
     |      >>> turtle.setpos(60,30)
     |      >>> turtle.pos()
     |      (60.00,30.00)
     |      >>> turtle.setpos((20,80))
     |      >>> turtle.pos()
     |      (20.00,80.00)
     |      >>> turtle.setpos(tp)
     |      >>> turtle.pos()
     |      (0.00,0.00)
     |  
     |  heading(self)
     |      Return the turtle's current heading.
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.left(67)
     |      >>> turtle.heading()
     |      67.0
     |  
     |  home(self)
     |      Move turtle to the origin - coordinates (0,0).
     |      
     |      No arguments.
     |      
     |      Move turtle to the origin - coordinates (0,0) and set its
     |      heading to its start-orientation (which depends on mode).
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.home()
     |  
     |  left(self, angle)
     |      Turn turtle left by angle units.
     |      
     |      Aliases: left | lt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle left by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.left(45)
     |      >>> turtle.heading()
     |      67.0
     |  
     |  lt = left(self, angle)
     |      Turn turtle left by angle units.
     |      
     |      Aliases: left | lt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle left by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.left(45)
     |      >>> turtle.heading()
     |      67.0
     |  
     |  pos(self)
     |      Return the turtle's current location (x,y), as a Vec2D-vector.
     |      
     |      Aliases: pos | position
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (0.00, 240.00)
     |  
     |  position = pos(self)
     |      Return the turtle's current location (x,y), as a Vec2D-vector.
     |      
     |      Aliases: pos | position
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (0.00, 240.00)
     |  
     |  radians(self)
     |      Set the angle measurement units to radians.
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      90
     |      >>> turtle.radians()
     |      >>> turtle.heading()
     |      1.5707963267948966
     |  
     |  right(self, angle)
     |      Turn turtle right by angle units.
     |      
     |      Aliases: right | rt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle right by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.right(45)
     |      >>> turtle.heading()
     |      337.0
     |  
     |  rt = right(self, angle)
     |      Turn turtle right by angle units.
     |      
     |      Aliases: right | rt
     |      
     |      Argument:
     |      angle -- a number (integer or float)
     |      
     |      Turn turtle right by angle units. (Units are by default degrees,
     |      but can be set via the degrees() and radians() functions.)
     |      Angle orientation depends on mode. (See this.)
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.heading()
     |      22.0
     |      >>> turtle.right(45)
     |      >>> turtle.heading()
     |      337.0
     |  
     |  seth = setheading(self, to_angle)
     |      Set the orientation of the turtle to to_angle.
     |      
     |      Aliases:  setheading | seth
     |      
     |      Argument:
     |      to_angle -- a number (integer or float)
     |      
     |      Set the orientation of the turtle to to_angle.
     |      Here are some common directions in degrees:
     |      
     |       standard - mode:          logo-mode:
     |      -------------------|--------------------
     |         0 - east                0 - north
     |        90 - north              90 - east
     |       180 - west              180 - south
     |       270 - south             270 - west
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.setheading(90)
     |      >>> turtle.heading()
     |      90
     |  
     |  setheading(self, to_angle)
     |      Set the orientation of the turtle to to_angle.
     |      
     |      Aliases:  setheading | seth
     |      
     |      Argument:
     |      to_angle -- a number (integer or float)
     |      
     |      Set the orientation of the turtle to to_angle.
     |      Here are some common directions in degrees:
     |      
     |       standard - mode:          logo-mode:
     |      -------------------|--------------------
     |         0 - east                0 - north
     |        90 - north              90 - east
     |       180 - west              180 - south
     |       270 - south             270 - west
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.setheading(90)
     |      >>> turtle.heading()
     |      90
     |  
     |  setpos = goto(self, x, y=None)
     |      Move turtle to an absolute position.
     |      
     |      Aliases: setpos | setposition | goto:
     |      
     |      Arguments:
     |      x -- a number      or     a pair/vector of numbers
     |      y -- a number             None
     |      
     |      call: goto(x, y)         # two coordinates
     |      --or: goto((x, y))       # a pair (tuple) of coordinates
     |      --or: goto(vec)          # e.g. as returned by pos()
     |      
     |      Move turtle to an absolute position. If the pen is down,
     |      a line will be drawn. The turtle's orientation does not change.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> tp = turtle.pos()
     |      >>> tp
     |      (0.00, 0.00)
     |      >>> turtle.setpos(60,30)
     |      >>> turtle.pos()
     |      (60.00,30.00)
     |      >>> turtle.setpos((20,80))
     |      >>> turtle.pos()
     |      (20.00,80.00)
     |      >>> turtle.setpos(tp)
     |      >>> turtle.pos()
     |      (0.00,0.00)
     |  
     |  setposition = goto(self, x, y=None)
     |      Move turtle to an absolute position.
     |      
     |      Aliases: setpos | setposition | goto:
     |      
     |      Arguments:
     |      x -- a number      or     a pair/vector of numbers
     |      y -- a number             None
     |      
     |      call: goto(x, y)         # two coordinates
     |      --or: goto((x, y))       # a pair (tuple) of coordinates
     |      --or: goto(vec)          # e.g. as returned by pos()
     |      
     |      Move turtle to an absolute position. If the pen is down,
     |      a line will be drawn. The turtle's orientation does not change.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> tp = turtle.pos()
     |      >>> tp
     |      (0.00, 0.00)
     |      >>> turtle.setpos(60,30)
     |      >>> turtle.pos()
     |      (60.00,30.00)
     |      >>> turtle.setpos((20,80))
     |      >>> turtle.pos()
     |      (20.00,80.00)
     |      >>> turtle.setpos(tp)
     |      >>> turtle.pos()
     |      (0.00,0.00)
     |  
     |  setx(self, x)
     |      Set the turtle's first coordinate to x
     |      
     |      Argument:
     |      x -- a number (integer or float)
     |      
     |      Set the turtle's first coordinate to x, leave second coordinate
     |      unchanged.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 240.00)
     |      >>> turtle.setx(10)
     |      >>> turtle.position()
     |      (10.00, 240.00)
     |  
     |  sety(self, y)
     |      Set the turtle's second coordinate to y
     |      
     |      Argument:
     |      y -- a number (integer or float)
     |      
     |      Set the turtle's first coordinate to x, second coordinate remains
     |      unchanged.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.position()
     |      (0.00, 40.00)
     |      >>> turtle.sety(-10)
     |      >>> turtle.position()
     |      (0.00, -10.00)
     |  
     |  towards(self, x, y=None)
     |      Return the angle of the line from the turtle's position to (x, y).
     |      
     |      Arguments:
     |      x -- a number   or  a pair/vector of numbers   or   a turtle instance
     |      y -- a number       None                            None
     |      
     |      call: distance(x, y)         # two coordinates
     |      --or: distance((x, y))       # a pair (tuple) of coordinates
     |      --or: distance(vec)          # e.g. as returned by pos()
     |      --or: distance(mypen)        # where mypen is another turtle
     |      
     |      Return the angle, between the line from turtle-position to position
     |      specified by x, y and the turtle's start orientation. (Depends on
     |      modes - "standard" or "logo")
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.pos()
     |      (10.00, 10.00)
     |      >>> turtle.towards(0,0)
     |      225.0
     |  
     |  xcor(self)
     |      Return the turtle's x coordinate.
     |      
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> reset()
     |      >>> turtle.left(60)
     |      >>> turtle.forward(100)
     |      >>> print turtle.xcor()
     |      50.0
     |  
     |  ycor(self)
     |      Return the turtle's y coordinate
     |      ---
     |      No arguments.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> reset()
     |      >>> turtle.left(60)
     |      >>> turtle.forward(100)
     |      >>> print turtle.ycor()
     |      86.6025403784
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes inherited from TNavigator:
     |  
     |  DEFAULT_ANGLEOFFSET = 0
     |  
     |  DEFAULT_ANGLEORIENT = 1
     |  
     |  DEFAULT_MODE = 'standard'
     |  
     |  START_ORIENTATION = {'logo': (0.00,1.00), 'standard': (1.00,0.00), 'wo...
    
    class ScrolledCanvas(tkinter.Frame)
     |  Modeled after the scrolled canvas class from Grayons's Tkinter book.
     |  
     |  Used as the default canvas, which pops up automatically when
     |  using turtle graphics functions or the Turtle class.
     |  
     |  Method resolution order:
     |      ScrolledCanvas
     |      tkinter.Frame
     |      tkinter.Widget
     |      tkinter.BaseWidget
     |      tkinter.Misc
     |      tkinter.Pack
     |      tkinter.Place
     |      tkinter.Grid
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, master, width=500, height=350, canvwidth=600, canvheight=500)
     |      Construct a frame widget with the parent MASTER.
     |      
     |      Valid resource names: background, bd, bg, borderwidth, class,
     |      colormap, container, cursor, height, highlightbackground,
     |      highlightcolor, highlightthickness, relief, takefocus, visual, width.
     |  
     |  addtag(self, *args, **kw)
     |  
     |  addtag_above(self, *args, **kw)
     |  
     |  addtag_all(self, *args, **kw)
     |  
     |  addtag_below(self, *args, **kw)
     |  
     |  addtag_closest(self, *args, **kw)
     |  
     |  addtag_enclosed(self, *args, **kw)
     |  
     |  addtag_overlapping(self, *args, **kw)
     |  
     |  addtag_withtag(self, *args, **kw)
     |  
     |  adjustScrolls(self)
     |      Adjust scrollbars according to window- and canvas-size.
     |  
     |  bbox(self, *args)
     |      'forward' method, which canvas itself has inherited...
     |  
     |  bind(self, *args, **kwargs)
     |      'forward' method, which canvas itself has inherited...
     |  
     |  canvasx(self, *args, **kw)
     |  
     |  canvasy(self, *args, **kw)
     |  
     |  cget(self, *args, **kwargs)
     |      'forward' method, which canvas itself has inherited...
     |  
     |  config(self, *args, **kwargs)
     |      'forward' method, which canvas itself has inherited...
     |  
     |  coords(self, *args, **kw)
     |  
     |  create_arc(self, *args, **kw)
     |  
     |  create_bitmap(self, *args, **kw)
     |  
     |  create_image(self, *args, **kw)
     |  
     |  create_line(self, *args, **kw)
     |  
     |  create_oval(self, *args, **kw)
     |  
     |  create_polygon(self, *args, **kw)
     |  
     |  create_rectangle(self, *args, **kw)
     |  
     |  create_text(self, *args, **kw)
     |  
     |  create_window(self, *args, **kw)
     |  
     |  dchars(self, *args, **kw)
     |  
     |  delete(self, *args, **kw)
     |  
     |  dtag(self, *args, **kw)
     |  
     |  find(self, *args, **kw)
     |  
     |  find_above(self, *args, **kw)
     |  
     |  find_all(self, *args, **kw)
     |  
     |  find_below(self, *args, **kw)
     |  
     |  find_closest(self, *args, **kw)
     |  
     |  find_enclosed(self, *args, **kw)
     |  
     |  find_overlapping(self, *args, **kw)
     |  
     |  find_withtag(self, *args, **kw)
     |  
     |  focus_force(self)
     |      'forward' method, which canvas itself has inherited...
     |  
     |  gettags(self, *args, **kw)
     |  
     |  icursor(self, *args, **kw)
     |  
     |  index(self, *args, **kw)
     |  
     |  insert(self, *args, **kw)
     |  
     |  itemcget(self, *args, **kw)
     |  
     |  itemconfig(self, *args, **kw)
     |  
     |  itemconfigure(self, *args, **kw)
     |  
     |  move(self, *args, **kw)
     |  
     |  onResize(self, event)
     |      self-explanatory
     |  
     |  postscript(self, *args, **kw)
     |  
     |  reset(self, canvwidth=None, canvheight=None, bg=None)
     |      Adjust canvas and scrollbars according to given canvas size.
     |  
     |  scale(self, *args, **kw)
     |  
     |  scan_dragto(self, *args, **kw)
     |  
     |  scan_mark(self, *args, **kw)
     |  
     |  select_adjust(self, *args, **kw)
     |  
     |  select_clear(self, *args, **kw)
     |  
     |  select_from(self, *args, **kw)
     |  
     |  select_item(self, *args, **kw)
     |  
     |  select_to(self, *args, **kw)
     |  
     |  tag_bind(self, *args, **kw)
     |  
     |  tag_lower(self, *args, **kw)
     |  
     |  tag_raise(self, *args, **kw)
     |  
     |  tag_unbind(self, *args, **kw)
     |  
     |  type(self, *args, **kw)
     |  
     |  unbind(self, *args, **kwargs)
     |      'forward' method, which canvas itself has inherited...
     |  
     |  xview(self, *args, **kw)
     |  
     |  xview_moveto(self, *args, **kw)
     |  
     |  xview_scroll(self, *args, **kw)
     |  
     |  yview(self, *args, **kw)
     |  
     |  yview_moveto(self, *args, **kw)
     |  
     |  yview_scroll(self, *args, **kw)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from tkinter.BaseWidget:
     |  
     |  destroy(self)
     |      Destroy this and all descendants widgets.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from tkinter.Misc:
     |  
     |  __getitem__ = cget(self, key)
     |      Return the resource value for a KEY given as string.
     |  
     |  __repr__(self)
     |      Return repr(self).
     |  
     |  __setitem__(self, key, value)
     |  
     |  __str__(self)
     |      Return the window path name of this widget.
     |  
     |  after(self, ms, func=None, *args)
     |      Call function once after given time.
     |      
     |      MS specifies the time in milliseconds. FUNC gives the
     |      function which shall be called. Additional parameters
     |      are given as parameters to the function call.  Return
     |      identifier to cancel scheduling with after_cancel.
     |  
     |  after_cancel(self, id)
     |      Cancel scheduling of function identified with ID.
     |      
     |      Identifier returned by after or after_idle must be
     |      given as first parameter.
     |  
     |  after_idle(self, func, *args)
     |      Call FUNC once if the Tcl main loop has no event to
     |      process.
     |      
     |      Return an identifier to cancel the scheduling with
     |      after_cancel.
     |  
     |  anchor = grid_anchor(self, anchor=None)
     |      The anchor value controls how to place the grid within the
     |      master when no row/column has any weight.
     |      
     |      The default anchor is nw.
     |  
     |  bell(self, displayof=0)
     |      Ring a display's bell.
     |  
     |  bind_all(self, sequence=None, func=None, add=None)
     |      Bind to all widgets at an event SEQUENCE a call to function FUNC.
     |      An additional boolean parameter ADD specifies whether FUNC will
     |      be called additionally to the other bound function or whether
     |      it will replace the previous function. See bind for the return value.
     |  
     |  bind_class(self, className, sequence=None, func=None, add=None)
     |      Bind to widgets with bindtag CLASSNAME at event
     |      SEQUENCE a call of function FUNC. An additional
     |      boolean parameter ADD specifies whether FUNC will be
     |      called additionally to the other bound function or
     |      whether it will replace the previous function. See bind for
     |      the return value.
     |  
     |  bindtags(self, tagList=None)
     |      Set or get the list of bindtags for this widget.
     |      
     |      With no argument return the list of all bindtags associated with
     |      this widget. With a list of strings as argument the bindtags are
     |      set to this list. The bindtags determine in which order events are
     |      processed (see bind).
     |  
     |  clipboard_append(self, string, **kw)
     |      Append STRING to the Tk clipboard.
     |      
     |      A widget specified at the optional displayof keyword
     |      argument specifies the target display. The clipboard
     |      can be retrieved with selection_get.
     |  
     |  clipboard_clear(self, **kw)
     |      Clear the data in the Tk clipboard.
     |      
     |      A widget specified for the optional displayof keyword
     |      argument specifies the target display.
     |  
     |  clipboard_get(self, **kw)
     |      Retrieve data from the clipboard on window's display.
     |      
     |      The window keyword defaults to the root window of the Tkinter
     |      application.
     |      
     |      The type keyword specifies the form in which the data is
     |      to be returned and should be an atom name such as STRING
     |      or FILE_NAME.  Type defaults to STRING, except on X11, where the default
     |      is to try UTF8_STRING and fall back to STRING.
     |      
     |      This command is equivalent to:
     |      
     |      selection_get(CLIPBOARD)
     |  
     |  columnconfigure = grid_columnconfigure(self, index, cnf={}, **kw)
     |      Configure column INDEX of a grid.
     |      
     |      Valid resources are minsize (minimum size of the column),
     |      weight (how much does additional space propagate to this column)
     |      and pad (how much space to let additionally).
     |  
     |  configure(self, cnf=None, **kw)
     |      Configure resources of a widget.
     |      
     |      The values for resources are specified as keyword
     |      arguments. To get an overview about
     |      the allowed keyword arguments call the method keys.
     |  
     |  deletecommand(self, name)
     |      Internal function.
     |      
     |      Delete the Tcl command provided in NAME.
     |  
     |  event_add(self, virtual, *sequences)
     |      Bind a virtual event VIRTUAL (of the form <<Name>>)
     |      to an event SEQUENCE such that the virtual event is triggered
     |      whenever SEQUENCE occurs.
     |  
     |  event_delete(self, virtual, *sequences)
     |      Unbind a virtual event VIRTUAL from SEQUENCE.
     |  
     |  event_generate(self, sequence, **kw)
     |      Generate an event SEQUENCE. Additional
     |      keyword arguments specify parameter of the event
     |      (e.g. x, y, rootx, rooty).
     |  
     |  event_info(self, virtual=None)
     |      Return a list of all virtual events or the information
     |      about the SEQUENCE bound to the virtual event VIRTUAL.
     |  
     |  focus = focus_set(self)
     |      Direct input focus to this widget.
     |      
     |      If the application currently does not have the focus
     |      this widget will get the focus if the application gets
     |      the focus through the window manager.
     |  
     |  focus_displayof(self)
     |      Return the widget which has currently the focus on the
     |      display where this widget is located.
     |      
     |      Return None if the application does not have the focus.
     |  
     |  focus_get(self)
     |      Return the widget which has currently the focus in the
     |      application.
     |      
     |      Use focus_displayof to allow working with several
     |      displays. Return None if application does not have
     |      the focus.
     |  
     |  focus_lastfor(self)
     |      Return the widget which would have the focus if top level
     |      for this widget gets the focus from the window manager.
     |  
     |  focus_set(self)
     |      Direct input focus to this widget.
     |      
     |      If the application currently does not have the focus
     |      this widget will get the focus if the application gets
     |      the focus through the window manager.
     |  
     |  getboolean(self, s)
     |      Return a boolean value for Tcl boolean values true and false given as parameter.
     |  
     |  getdouble(self, s)
     |  
     |  getint(self, s)
     |  
     |  getvar(self, name='PY_VAR')
     |      Return value of Tcl variable NAME.
     |  
     |  grab_current(self)
     |      Return widget which has currently the grab in this application
     |      or None.
     |  
     |  grab_release(self)
     |      Release grab for this widget if currently set.
     |  
     |  grab_set(self)
     |      Set grab for this widget.
     |      
     |      A grab directs all events to this and descendant
     |      widgets in the application.
     |  
     |  grab_set_global(self)
     |      Set global grab for this widget.
     |      
     |      A global grab directs all events to this and
     |      descendant widgets on the display. Use with caution -
     |      other applications do not get events anymore.
     |  
     |  grab_status(self)
     |      Return None, "local" or "global" if this widget has
     |      no, a local or a global grab.
     |  
     |  grid_anchor(self, anchor=None)
     |      The anchor value controls how to place the grid within the
     |      master when no row/column has any weight.
     |      
     |      The default anchor is nw.
     |  
     |  grid_bbox(self, column=None, row=None, col2=None, row2=None)
     |      Return a tuple of integer coordinates for the bounding
     |      box of this widget controlled by the geometry manager grid.
     |      
     |      If COLUMN, ROW is given the bounding box applies from
     |      the cell with row and column 0 to the specified
     |      cell. If COL2 and ROW2 are given the bounding box
     |      starts at that cell.
     |      
     |      The returned integers specify the offset of the upper left
     |      corner in the master widget and the width and height.
     |  
     |  grid_columnconfigure(self, index, cnf={}, **kw)
     |      Configure column INDEX of a grid.
     |      
     |      Valid resources are minsize (minimum size of the column),
     |      weight (how much does additional space propagate to this column)
     |      and pad (how much space to let additionally).
     |  
     |  grid_location(self, x, y)
     |      Return a tuple of column and row which identify the cell
     |      at which the pixel at position X and Y inside the master
     |      widget is located.
     |  
     |  grid_propagate(self, flag=['_noarg_'])
     |      Set or get the status for propagation of geometry information.
     |      
     |      A boolean argument specifies whether the geometry information
     |      of the slaves will determine the size of this widget. If no argument
     |      is given, the current setting will be returned.
     |  
     |  grid_rowconfigure(self, index, cnf={}, **kw)
     |      Configure row INDEX of a grid.
     |      
     |      Valid resources are minsize (minimum size of the row),
     |      weight (how much does additional space propagate to this row)
     |      and pad (how much space to let additionally).
     |  
     |  grid_size(self)
     |      Return a tuple of the number of column and rows in the grid.
     |  
     |  grid_slaves(self, row=None, column=None)
     |      Return a list of all slaves of this widget
     |      in its packing order.
     |  
     |  image_names(self)
     |      Return a list of all existing image names.
     |  
     |  image_types(self)
     |      Return a list of all available image types (e.g. phote bitmap).
     |  
     |  keys(self)
     |      Return a list of all resource names of this widget.
     |  
     |  lift = tkraise(self, aboveThis=None)
     |      Raise this widget in the stacking order.
     |  
     |  lower(self, belowThis=None)
     |      Lower this widget in the stacking order.
     |  
     |  mainloop(self, n=0)
     |      Call the mainloop of Tk.
     |  
     |  nametowidget(self, name)
     |      Return the Tkinter instance of a widget identified by
     |      its Tcl name NAME.
     |  
     |  option_add(self, pattern, value, priority=None)
     |      Set a VALUE (second parameter) for an option
     |      PATTERN (first parameter).
     |      
     |      An optional third parameter gives the numeric priority
     |      (defaults to 80).
     |  
     |  option_clear(self)
     |      Clear the option database.
     |      
     |      It will be reloaded if option_add is called.
     |  
     |  option_get(self, name, className)
     |      Return the value for an option NAME for this widget
     |      with CLASSNAME.
     |      
     |      Values with higher priority override lower values.
     |  
     |  option_readfile(self, fileName, priority=None)
     |      Read file FILENAME into the option database.
     |      
     |      An optional second parameter gives the numeric
     |      priority.
     |  
     |  pack_propagate(self, flag=['_noarg_'])
     |      Set or get the status for propagation of geometry information.
     |      
     |      A boolean argument specifies whether the geometry information
     |      of the slaves will determine the size of this widget. If no argument
     |      is given the current setting will be returned.
     |  
     |  pack_slaves(self)
     |      Return a list of all slaves of this widget
     |      in its packing order.
     |  
     |  place_slaves(self)
     |      Return a list of all slaves of this widget
     |      in its packing order.
     |  
     |  propagate = pack_propagate(self, flag=['_noarg_'])
     |      Set or get the status for propagation of geometry information.
     |      
     |      A boolean argument specifies whether the geometry information
     |      of the slaves will determine the size of this widget. If no argument
     |      is given the current setting will be returned.
     |  
     |  quit(self)
     |      Quit the Tcl interpreter. All widgets will be destroyed.
     |  
     |  register = _register(self, func, subst=None, needcleanup=1)
     |      Return a newly created Tcl function. If this
     |      function is called, the Python function FUNC will
     |      be executed. An optional function SUBST can
     |      be given which will be executed before FUNC.
     |  
     |  rowconfigure = grid_rowconfigure(self, index, cnf={}, **kw)
     |      Configure row INDEX of a grid.
     |      
     |      Valid resources are minsize (minimum size of the row),
     |      weight (how much does additional space propagate to this row)
     |      and pad (how much space to let additionally).
     |  
     |  selection_clear(self, **kw)
     |      Clear the current X selection.
     |  
     |  selection_get(self, **kw)
     |      Return the contents of the current X selection.
     |      
     |      A keyword parameter selection specifies the name of
     |      the selection and defaults to PRIMARY.  A keyword
     |      parameter displayof specifies a widget on the display
     |      to use. A keyword parameter type specifies the form of data to be
     |      fetched, defaulting to STRING except on X11, where UTF8_STRING is tried
     |      before STRING.
     |  
     |  selection_handle(self, command, **kw)
     |      Specify a function COMMAND to call if the X
     |      selection owned by this widget is queried by another
     |      application.
     |      
     |      This function must return the contents of the
     |      selection. The function will be called with the
     |      arguments OFFSET and LENGTH which allows the chunking
     |      of very long selections. The following keyword
     |      parameters can be provided:
     |      selection - name of the selection (default PRIMARY),
     |      type - type of the selection (e.g. STRING, FILE_NAME).
     |  
     |  selection_own(self, **kw)
     |      Become owner of X selection.
     |      
     |      A keyword parameter selection specifies the name of
     |      the selection (default PRIMARY).
     |  
     |  selection_own_get(self, **kw)
     |      Return owner of X selection.
     |      
     |      The following keyword parameter can
     |      be provided:
     |      selection - name of the selection (default PRIMARY),
     |      type - type of the selection (e.g. STRING, FILE_NAME).
     |  
     |  send(self, interp, cmd, *args)
     |      Send Tcl command CMD to different interpreter INTERP to be executed.
     |  
     |  setvar(self, name='PY_VAR', value='1')
     |      Set Tcl variable NAME to VALUE.
     |  
     |  size = grid_size(self)
     |      Return a tuple of the number of column and rows in the grid.
     |  
     |  slaves = pack_slaves(self)
     |      Return a list of all slaves of this widget
     |      in its packing order.
     |  
     |  tk_bisque(self)
     |      Change the color scheme to light brown as used in Tk 3.6 and before.
     |  
     |  tk_focusFollowsMouse(self)
     |      The widget under mouse will get automatically focus. Can not
     |      be disabled easily.
     |  
     |  tk_focusNext(self)
     |      Return the next widget in the focus order which follows
     |      widget which has currently the focus.
     |      
     |      The focus order first goes to the next child, then to
     |      the children of the child recursively and then to the
     |      next sibling which is higher in the stacking order.  A
     |      widget is omitted if it has the takefocus resource set
     |      to 0.
     |  
     |  tk_focusPrev(self)
     |      Return previous widget in the focus order. See tk_focusNext for details.
     |  
     |  tk_setPalette(self, *args, **kw)
     |      Set a new color scheme for all widget elements.
     |      
     |      A single color as argument will cause that all colors of Tk
     |      widget elements are derived from this.
     |      Alternatively several keyword parameters and its associated
     |      colors can be given. The following keywords are valid:
     |      activeBackground, foreground, selectColor,
     |      activeForeground, highlightBackground, selectBackground,
     |      background, highlightColor, selectForeground,
     |      disabledForeground, insertBackground, troughColor.
     |  
     |  tk_strictMotif(self, boolean=None)
     |      Set Tcl internal variable, whether the look and feel
     |      should adhere to Motif.
     |      
     |      A parameter of 1 means adhere to Motif (e.g. no color
     |      change if mouse passes over slider).
     |      Returns the set value.
     |  
     |  tkraise(self, aboveThis=None)
     |      Raise this widget in the stacking order.
     |  
     |  unbind_all(self, sequence)
     |      Unbind for all widgets for event SEQUENCE all functions.
     |  
     |  unbind_class(self, className, sequence)
     |      Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE
     |      all functions.
     |  
     |  update(self)
     |      Enter event loop until all pending events have been processed by Tcl.
     |  
     |  update_idletasks(self)
     |      Enter event loop until all idle callbacks have been called. This
     |      will update the display of windows but not process events caused by
     |      the user.
     |  
     |  wait_variable(self, name='PY_VAR')
     |      Wait until the variable is modified.
     |      
     |      A parameter of type IntVar, StringVar, DoubleVar or
     |      BooleanVar must be given.
     |  
     |  wait_visibility(self, window=None)
     |      Wait until the visibility of a WIDGET changes
     |      (e.g. it appears).
     |      
     |      If no parameter is given self is used.
     |  
     |  wait_window(self, window=None)
     |      Wait until a WIDGET is destroyed.
     |      
     |      If no parameter is given self is used.
     |  
     |  waitvar = wait_variable(self, name='PY_VAR')
     |      Wait until the variable is modified.
     |      
     |      A parameter of type IntVar, StringVar, DoubleVar or
     |      BooleanVar must be given.
     |  
     |  winfo_atom(self, name, displayof=0)
     |      Return integer which represents atom NAME.
     |  
     |  winfo_atomname(self, id, displayof=0)
     |      Return name of atom with identifier ID.
     |  
     |  winfo_cells(self)
     |      Return number of cells in the colormap for this widget.
     |  
     |  winfo_children(self)
     |      Return a list of all widgets which are children of this widget.
     |  
     |  winfo_class(self)
     |      Return window class name of this widget.
     |  
     |  winfo_colormapfull(self)
     |      Return true if at the last color request the colormap was full.
     |  
     |  winfo_containing(self, rootX, rootY, displayof=0)
     |      Return the widget which is at the root coordinates ROOTX, ROOTY.
     |  
     |  winfo_depth(self)
     |      Return the number of bits per pixel.
     |  
     |  winfo_exists(self)
     |      Return true if this widget exists.
     |  
     |  winfo_fpixels(self, number)
     |      Return the number of pixels for the given distance NUMBER
     |      (e.g. "3c") as float.
     |  
     |  winfo_geometry(self)
     |      Return geometry string for this widget in the form "widthxheight+X+Y".
     |  
     |  winfo_height(self)
     |      Return height of this widget.
     |  
     |  winfo_id(self)
     |      Return identifier ID for this widget.
     |  
     |  winfo_interps(self, displayof=0)
     |      Return the name of all Tcl interpreters for this display.
     |  
     |  winfo_ismapped(self)
     |      Return true if this widget is mapped.
     |  
     |  winfo_manager(self)
     |      Return the window mananger name for this widget.
     |  
     |  winfo_name(self)
     |      Return the name of this widget.
     |  
     |  winfo_parent(self)
     |      Return the name of the parent of this widget.
     |  
     |  winfo_pathname(self, id, displayof=0)
     |      Return the pathname of the widget given by ID.
     |  
     |  winfo_pixels(self, number)
     |      Rounded integer value of winfo_fpixels.
     |  
     |  winfo_pointerx(self)
     |      Return the x coordinate of the pointer on the root window.
     |  
     |  winfo_pointerxy(self)
     |      Return a tuple of x and y coordinates of the pointer on the root window.
     |  
     |  winfo_pointery(self)
     |      Return the y coordinate of the pointer on the root window.
     |  
     |  winfo_reqheight(self)
     |      Return requested height of this widget.
     |  
     |  winfo_reqwidth(self)
     |      Return requested width of this widget.
     |  
     |  winfo_rgb(self, color)
     |      Return tuple of decimal values for red, green, blue for
     |      COLOR in this widget.
     |  
     |  winfo_rootx(self)
     |      Return x coordinate of upper left corner of this widget on the
     |      root window.
     |  
     |  winfo_rooty(self)
     |      Return y coordinate of upper left corner of this widget on the
     |      root window.
     |  
     |  winfo_screen(self)
     |      Return the screen name of this widget.
     |  
     |  winfo_screencells(self)
     |      Return the number of the cells in the colormap of the screen
     |      of this widget.
     |  
     |  winfo_screendepth(self)
     |      Return the number of bits per pixel of the root window of the
     |      screen of this widget.
     |  
     |  winfo_screenheight(self)
     |      Return the number of pixels of the height of the screen of this widget
     |      in pixel.
     |  
     |  winfo_screenmmheight(self)
     |      Return the number of pixels of the height of the screen of
     |      this widget in mm.
     |  
     |  winfo_screenmmwidth(self)
     |      Return the number of pixels of the width of the screen of
     |      this widget in mm.
     |  
     |  winfo_screenvisual(self)
     |      Return one of the strings directcolor, grayscale, pseudocolor,
     |      staticcolor, staticgray, or truecolor for the default
     |      colormodel of this screen.
     |  
     |  winfo_screenwidth(self)
     |      Return the number of pixels of the width of the screen of
     |      this widget in pixel.
     |  
     |  winfo_server(self)
     |      Return information of the X-Server of the screen of this widget in
     |      the form "XmajorRminor vendor vendorVersion".
     |  
     |  winfo_toplevel(self)
     |      Return the toplevel widget of this widget.
     |  
     |  winfo_viewable(self)
     |      Return true if the widget and all its higher ancestors are mapped.
     |  
     |  winfo_visual(self)
     |      Return one of the strings directcolor, grayscale, pseudocolor,
     |      staticcolor, staticgray, or truecolor for the
     |      colormodel of this widget.
     |  
     |  winfo_visualid(self)
     |      Return the X identifier for the visual for this widget.
     |  
     |  winfo_visualsavailable(self, includeids=False)
     |      Return a list of all visuals available for the screen
     |      of this widget.
     |      
     |      Each item in the list consists of a visual name (see winfo_visual), a
     |      depth and if includeids is true is given also the X identifier.
     |  
     |  winfo_vrootheight(self)
     |      Return the height of the virtual root window associated with this
     |      widget in pixels. If there is no virtual root window return the
     |      height of the screen.
     |  
     |  winfo_vrootwidth(self)
     |      Return the width of the virtual root window associated with this
     |      widget in pixel. If there is no virtual root window return the
     |      width of the screen.
     |  
     |  winfo_vrootx(self)
     |      Return the x offset of the virtual root relative to the root
     |      window of the screen of this widget.
     |  
     |  winfo_vrooty(self)
     |      Return the y offset of the virtual root relative to the root
     |      window of the screen of this widget.
     |  
     |  winfo_width(self)
     |      Return the width of this widget.
     |  
     |  winfo_x(self)
     |      Return the x coordinate of the upper left corner of this widget
     |      in the parent.
     |  
     |  winfo_y(self)
     |      Return the y coordinate of the upper left corner of this widget
     |      in the parent.
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from tkinter.Misc:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from tkinter.Pack:
     |  
     |  forget = pack_forget(self)
     |      Unmap this widget and do not use it for the packing order.
     |  
     |  info = pack_info(self)
     |      Return information about the packing options
     |      for this widget.
     |  
     |  pack = pack_configure(self, cnf={}, **kw)
     |      Pack a widget in the parent widget. Use as options:
     |      after=widget - pack it after you have packed widget
     |      anchor=NSEW (or subset) - position widget according to
     |                                given direction
     |      before=widget - pack it before you will pack widget
     |      expand=bool - expand widget if parent size grows
     |      fill=NONE or X or Y or BOTH - fill widget if widget grows
     |      in=master - use master to contain this widget
     |      in_=master - see 'in' option description
     |      ipadx=amount - add internal padding in x direction
     |      ipady=amount - add internal padding in y direction
     |      padx=amount - add padding in x direction
     |      pady=amount - add padding in y direction
     |      side=TOP or BOTTOM or LEFT or RIGHT -  where to add this widget.
     |  
     |  pack_configure(self, cnf={}, **kw)
     |      Pack a widget in the parent widget. Use as options:
     |      after=widget - pack it after you have packed widget
     |      anchor=NSEW (or subset) - position widget according to
     |                                given direction
     |      before=widget - pack it before you will pack widget
     |      expand=bool - expand widget if parent size grows
     |      fill=NONE or X or Y or BOTH - fill widget if widget grows
     |      in=master - use master to contain this widget
     |      in_=master - see 'in' option description
     |      ipadx=amount - add internal padding in x direction
     |      ipady=amount - add internal padding in y direction
     |      padx=amount - add padding in x direction
     |      pady=amount - add padding in y direction
     |      side=TOP or BOTTOM or LEFT or RIGHT -  where to add this widget.
     |  
     |  pack_forget(self)
     |      Unmap this widget and do not use it for the packing order.
     |  
     |  pack_info(self)
     |      Return information about the packing options
     |      for this widget.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from tkinter.Place:
     |  
     |  place = place_configure(self, cnf={}, **kw)
     |      Place a widget in the parent widget. Use as options:
     |      in=master - master relative to which the widget is placed
     |      in_=master - see 'in' option description
     |      x=amount - locate anchor of this widget at position x of master
     |      y=amount - locate anchor of this widget at position y of master
     |      relx=amount - locate anchor of this widget between 0.0 and 1.0
     |                    relative to width of master (1.0 is right edge)
     |      rely=amount - locate anchor of this widget between 0.0 and 1.0
     |                    relative to height of master (1.0 is bottom edge)
     |      anchor=NSEW (or subset) - position anchor according to given direction
     |      width=amount - width of this widget in pixel
     |      height=amount - height of this widget in pixel
     |      relwidth=amount - width of this widget between 0.0 and 1.0
     |                        relative to width of master (1.0 is the same width
     |                        as the master)
     |      relheight=amount - height of this widget between 0.0 and 1.0
     |                         relative to height of master (1.0 is the same
     |                         height as the master)
     |      bordermode="inside" or "outside" - whether to take border width of
     |                                         master widget into account
     |  
     |  place_configure(self, cnf={}, **kw)
     |      Place a widget in the parent widget. Use as options:
     |      in=master - master relative to which the widget is placed
     |      in_=master - see 'in' option description
     |      x=amount - locate anchor of this widget at position x of master
     |      y=amount - locate anchor of this widget at position y of master
     |      relx=amount - locate anchor of this widget between 0.0 and 1.0
     |                    relative to width of master (1.0 is right edge)
     |      rely=amount - locate anchor of this widget between 0.0 and 1.0
     |                    relative to height of master (1.0 is bottom edge)
     |      anchor=NSEW (or subset) - position anchor according to given direction
     |      width=amount - width of this widget in pixel
     |      height=amount - height of this widget in pixel
     |      relwidth=amount - width of this widget between 0.0 and 1.0
     |                        relative to width of master (1.0 is the same width
     |                        as the master)
     |      relheight=amount - height of this widget between 0.0 and 1.0
     |                         relative to height of master (1.0 is the same
     |                         height as the master)
     |      bordermode="inside" or "outside" - whether to take border width of
     |                                         master widget into account
     |  
     |  place_forget(self)
     |      Unmap this widget.
     |  
     |  place_info(self)
     |      Return information about the placing options
     |      for this widget.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from tkinter.Grid:
     |  
     |  grid = grid_configure(self, cnf={}, **kw)
     |      Position a widget in the parent widget in a grid. Use as options:
     |      column=number - use cell identified with given column (starting with 0)
     |      columnspan=number - this widget will span several columns
     |      in=master - use master to contain this widget
     |      in_=master - see 'in' option description
     |      ipadx=amount - add internal padding in x direction
     |      ipady=amount - add internal padding in y direction
     |      padx=amount - add padding in x direction
     |      pady=amount - add padding in y direction
     |      row=number - use cell identified with given row (starting with 0)
     |      rowspan=number - this widget will span several rows
     |      sticky=NSEW - if cell is larger on which sides will this
     |                    widget stick to the cell boundary
     |  
     |  grid_configure(self, cnf={}, **kw)
     |      Position a widget in the parent widget in a grid. Use as options:
     |      column=number - use cell identified with given column (starting with 0)
     |      columnspan=number - this widget will span several columns
     |      in=master - use master to contain this widget
     |      in_=master - see 'in' option description
     |      ipadx=amount - add internal padding in x direction
     |      ipady=amount - add internal padding in y direction
     |      padx=amount - add padding in x direction
     |      pady=amount - add padding in y direction
     |      row=number - use cell identified with given row (starting with 0)
     |      rowspan=number - this widget will span several rows
     |      sticky=NSEW - if cell is larger on which sides will this
     |                    widget stick to the cell boundary
     |  
     |  grid_forget(self)
     |      Unmap this widget.
     |  
     |  grid_info(self)
     |      Return information about the options
     |      for positioning this widget in a grid.
     |  
     |  grid_remove(self)
     |      Unmap this widget but remember the grid options.
     |  
     |  location = grid_location(self, x, y)
     |      Return a tuple of column and row which identify the cell
     |      at which the pixel at position X and Y inside the master
     |      widget is located.
    
    class Shape(builtins.object)
     |  Data structure modeling shapes.
     |  
     |  attribute _type is one of "polygon", "image", "compound"
     |  attribute _data is - depending on _type a poygon-tuple,
     |  an image or a list constructed using the addcomponent method.
     |  
     |  Methods defined here:
     |  
     |  __init__(self, type_, data=None)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  addcomponent(self, poly, fill, outline=None)
     |      Add component to a shape of type compound.
     |      
     |      Arguments: poly is a polygon, i. e. a tuple of number pairs.
     |      fill is the fillcolor of the component,
     |      outline is the outline color of the component.
     |      
     |      call (for a Shapeobject namend s):
     |      --   s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue")
     |      
     |      Example:
     |      >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
     |      >>> s = Shape("compound")
     |      >>> s.addcomponent(poly, "red", "blue")
     |      >>> # .. add more components and then use register_shape()
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
    
    class Terminator(builtins.Exception)
     |  Will be raised in TurtleScreen.update, if _RUNNING becomes False.
     |  
     |  This stops execution of a turtle graphics script.
     |  Main purpose: use in the Demo-Viewer turtle.Demo.py.
     |  
     |  Method resolution order:
     |      Terminator
     |      builtins.Exception
     |      builtins.BaseException
     |      builtins.object
     |  
     |  Data descriptors defined here:
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from builtins.Exception:
     |  
     |  __init__(self, /, *args, **kwargs)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  __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
    
    class Turtle(RawTurtle)
     |  RawTurtle auto-creating (scrolled) canvas.
     |  
     |  When a Turtle object is created or a function derived from some
     |  Turtle method is called a TurtleScreen object is automatically created.
     |  
     |  Method resolution order:
     |      Turtle
     |      RawTurtle
     |      TPen
     |      TNavigator
     |      builtins.object
     |  
     |  Methods defined here:
     |  
     |  __init__(self, shape='classic', undobuffersize=1000, visible=True)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  ----------------------------------------------------------------------
     |  Methods inherited from RawTurtle:
     |  
     |  begin_fill(self)
     |      Called just before drawing a shape to be filled.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("black", "red")
     |      >>> turtle.begin_fill()
     |      >>> turtle.circle(60)
     |      >>> turtle.end_fill()
     |  
     |  begin_poly(self)
     |      Start recording the vertices of a polygon.
     |      
     |      No argument.
     |      
     |      Start recording the vertices of a polygon. Current turtle position
     |      is first point of polygon.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.begin_poly()
     |  
     |  clear(self)
     |      Delete the turtle's drawings from the screen. Do not move turtle.
     |      
     |      No arguments.
     |      
     |      Delete the turtle's drawings from the screen. Do not move turtle.
     |      State and position of the turtle as well as drawings of other
     |      turtles are not affected.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.clear()
     |  
     |  clearstamp(self, stampid)
     |      Delete stamp with given stampid
     |      
     |      Argument:
     |      stampid - an integer, must be return value of previous stamp() call.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("blue")
     |      >>> astamp = turtle.stamp()
     |      >>> turtle.fd(50)
     |      >>> turtle.clearstamp(astamp)
     |  
     |  clearstamps(self, n=None)
     |      Delete all or first/last n of turtle's stamps.
     |      
     |      Optional argument:
     |      n -- an integer
     |      
     |      If n is None, delete all of pen's stamps,
     |      else if n > 0 delete first n stamps
     |      else if n < 0 delete last n stamps.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> for i in range(8):
     |      ...     turtle.stamp(); turtle.fd(30)
     |      ...
     |      >>> turtle.clearstamps(2)
     |      >>> turtle.clearstamps(-2)
     |      >>> turtle.clearstamps()
     |  
     |  clone(self)
     |      Create and return a clone of the turtle.
     |      
     |      No argument.
     |      
     |      Create and return a clone of the turtle with same position, heading
     |      and turtle properties.
     |      
     |      Example (for a Turtle instance named mick):
     |      mick = Turtle()
     |      joe = mick.clone()
     |  
     |  dot(self, size=None, *color)
     |      Draw a dot with diameter size, using color.
     |      
     |      Optional arguments:
     |      size -- an integer >= 1 (if given)
     |      color -- a colorstring or a numeric color tuple
     |      
     |      Draw a circular dot with diameter size, using color.
     |      If size is not given, the maximum of pensize+4 and 2*pensize is used.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.dot()
     |      >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
     |  
     |  end_fill(self)
     |      Fill the shape drawn after the call begin_fill().
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.color("black", "red")
     |      >>> turtle.begin_fill()
     |      >>> turtle.circle(60)
     |      >>> turtle.end_fill()
     |  
     |  end_poly(self)
     |      Stop recording the vertices of a polygon.
     |      
     |      No argument.
     |      
     |      Stop recording the vertices of a polygon. Current turtle position is
     |      last point of polygon. This will be connected with the first point.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.end_poly()
     |  
     |  filling(self)
     |      Return fillstate (True if filling, False else).
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.begin_fill()
     |      >>> if turtle.filling():
     |      ...     turtle.pensize(5)
     |      ... else:
     |      ...     turtle.pensize(3)
     |  
     |  get_poly(self)
     |      Return the lastly recorded polygon.
     |      
     |      No argument.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> p = turtle.get_poly()
     |      >>> turtle.register_shape("myFavouriteShape", p)
     |  
     |  get_shapepoly(self)
     |      Return the current shape polygon as tuple of coordinate pairs.
     |      
     |      No argument.
     |      
     |      Examples (for a Turtle instance named turtle):
     |      >>> turtle.shape("square")
     |      >>> turtle.shapetransform(4, -1, 0, 2)
     |      >>> turtle.get_shapepoly()
     |      ((50, -20), (30, 20), (-50, 20), (-30, -20))
     |  
     |  getpen = getturtle(self)
     |      Return the Turtleobject itself.
     |      
     |      No argument.
     |      
     |      Only reasonable use: as a function to return the 'anonymous turtle':
     |      
     |      Example:
     |      >>> pet = getturtle()
     |      >>> pet.fd(50)
     |      >>> pet
     |      <turtle.Turtle object at 0x0187D810>
     |      >>> turtles()
     |      [<turtle.Turtle object at 0x0187D810>]
     |  
     |  getscreen(self)
     |      Return the TurtleScreen object, the turtle is drawing  on.
     |      
     |      No argument.
     |      
     |      Return the TurtleScreen object, the turtle is drawing  on.
     |      So TurtleScreen-methods can be called for that object.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> ts = turtle.getscreen()
     |      >>> ts
     |      <turtle.TurtleScreen object at 0x0106B770>
     |      >>> ts.bgcolor("pink")
     |  
     |  getturtle(self)
     |      Return the Turtleobject itself.
     |      
     |      No argument.
     |      
     |      Only reasonable use: as a function to return the 'anonymous turtle':
     |      
     |      Example:
     |      >>> pet = getturtle()
     |      >>> pet.fd(50)
     |      >>> pet
     |      <turtle.Turtle object at 0x0187D810>
     |      >>> turtles()
     |      [<turtle.Turtle object at 0x0187D810>]
     |  
     |  onclick(self, fun, btn=1, add=None)
     |      Bind fun to mouse-click event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun --  a function with two arguments, to which will be assigned
     |              the coordinates of the clicked point on the canvas.
     |      num --  number of the mouse-button defaults to 1 (left mouse button).
     |      add --  True or False. If True, new binding will be added, otherwise
     |              it will replace a former binding.
     |      
     |      Example for the anonymous turtle, i. e. the procedural way:
     |      
     |      >>> def turn(x, y):
     |      ...     left(360)
     |      ...
     |      >>> onclick(turn)  # Now clicking into the turtle will turn it.
     |      >>> onclick(None)  # event-binding will be removed
     |  
     |  ondrag(self, fun, btn=1, add=None)
     |      Bind fun to mouse-move event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun -- a function with two arguments, to which will be assigned
     |             the coordinates of the clicked point on the canvas.
     |      num -- number of the mouse-button defaults to 1 (left mouse button).
     |      
     |      Every sequence of mouse-move-events on a turtle is preceded by a
     |      mouse-click event on that turtle.
     |      
     |      Example (for a Turtle instance named turtle):
     |      >>> turtle.ondrag(turtle.goto)
     |      
     |      Subsequently clicking and dragging a Turtle will move it
     |      across the screen thereby producing handdrawings (if pen is
     |      down).
     |  
     |  onrelease(self, fun, btn=1, add=None)
     |      Bind fun to mouse-button-release event on this turtle on canvas.
     |      
     |      Arguments:
     |      fun -- a function with two arguments, to which will be assigned
     |