id
int64
0
25.6k
text
stringlengths
0
4.59k
7,300
member of the helmholtz association slide
7,301
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,302
if = print aha blocks are defined by indentation=style guide for python standardindentation with four spaces if = print spam elif = print eggs elif =- print bacon else print something else member of the helmholtz association slide
7,303
comparison of content=!comparison of object identitya is is not and/or operatora and or chained comparisona < = = negationnot if not = and ( < )pass hintpass is no operation (noopfunction member of the helmholtz association slide
7,304
for in range ( )print for in range ( )print for in range ( )print else print loop completed end loop prematurelybreak next iterationcontinue else is executed when loop didn' end prematurely member of the helmholtz association slide
7,305
iterating directly over sequences (without using an index)for item in spam eggs bacon ]print item the range function can be used to create listlist range ( )[ if indexes are necessaryfor ( char in enumerate hello world )print ( char member of the helmholtz association slide
7,306
while + break and continue work for while loopstoo substitute for do-while loopwhile true important code if condition break member of the helmholtz association slide
7,307
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,308
def add ( )""returns the sum of and ""mysum return mysum result add ( print result help add help on function add in module __main__ add ( returns the sum of and member of the helmholtz association slide
7,309
functions accept arbitrary objects as parameters and return values types of parameters and return values are unspecified functions without explicit return value return none my_program py def hello_world ()print hello world hello_world (print python my_program py hello world none member of the helmholtz association slide
7,310
multiple return values are realised using tuples or listsdef foo () return ( ret foo (( foo (member of the helmholtz association slide
7,311
parameters can be defined with default values hintit is not allowed to define non-default parameters after default parameters plot_lines py def fline ( = = ) return for in range ( )print fline end force newline print (for in range ( )print fline ( - , end python plot_lines py - - - hintend in print defines the last characterdefault is linebreak member of the helmholtz association slide
7,312
parameters can be passed to function in different order than specifieddisplayperson py def printcontact name age location )print person name print age age years print address location printcontact name peter pan location neverland age = python displayperson py person peter pan age years address neverland member of the helmholtz association slide
7,313
functions are objects and as such can be assigned and passed ona float ( def foo fkt )print fkt ( )foo float foo str foo complex ( + member of the helmholtz association slide
7,314
can be used in functionmodulclass and method definitions is defined by string as the first statement in the definition helpon python object returns the docstring two types of docstringsone-liners and multi-liners def complex real = imag = )""form complex number keyword arguments real -the real part default imag -the imaginary part default ""member of the helmholtz association slide
7,315
functions thematically belonging together can be stored in separate python file (same for objects and classesthis file is called module and can be loaded in any python script multiple modules available in the python standard library (part of the python installationcommand for loading moduleimport (filename without ending pyimport math math sin math pi more information for standard modules and how to create your own module see modules and packages on slide member of the helmholtz association slide
7,316
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,317
format string class method format("replacement fields"curly braces around optional arg_name (default , , print the answer is { : format ( )the answer is { }{ : format spam spam format nf ne nmd purpose defaultstring floating pointm filed sizen digits after the decimal point ( floating point (exponential) filed size digit before and digits behind the decimal point (default percentagesimilar to format fvalue with finalizing '%integer numberm field size ( =leading " "format can be replaced by (binary) (octalor (hexadecimalmember of the helmholtz association slide
7,318
provides way to embed expressions inside string literalsusing minimal syntax is literal stringprefixed with ' 'which contains expressions inside braces expressions are evaluated at runtime and replaced with their values name martin age my name is name and my age next year is age + my name is martin and my age next year is value value =value : value = hintsince python member of the helmholtz association slide
7,319
string formatting similar to cprint the answer is % % spam integer decimaldi integer octalo integer hexadecimalxx floatff float in exponential formeegg single characterc strings use %to output single character member of the helmholtz association slide
7,320
user input in python user_input input type something user input in python user_input raw_input type something hintin python is input("=eval(raw_input(")command line parametersparams py import sys print sys argv python params py spam params py spam 'member of the helmholtz association slide
7,321
file open spam txt file open tmp eggs json wb read moder write mode (new file) write modeappending to the enda handling binary filese rb read and write (update)rfor line in file print line member of the helmholtz association slide
7,322
readf read([size]read linef readline(read multiple linesf readlines([sizehint]writef write(strwrite multiple linesf writelines(sequenceclose filef close(file open test txt lines spam eggs ham file writelines lines file close (python automatically converts \ into the correct line endingmember of the helmholtz association slide
7,323
file handling (open/closecan be done by the context manager with (=section errors and exceptions on slide with open test txt as for line in print line after finishing the with block the file object is closedeven if an exception occurred inside the block member of the helmholtz association slide
7,324
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,325
parsing errorsprogram will not be executed mismatched or missing parenthesis missing or misplaced semicolonscolonscommas indentation errors add py print ' running def add ( return python add py file add py line def add ( syntaxerror invalid syntax member of the helmholtz association slide
7,326
exceptions occur at runtimeerror py import math print ' running math foo (print ' still running python error py running traceback most recent call last )file error py line in math foo (attributeerror module math has no attribute 'foo member of the helmholtz association slide
7,327
try input enter number number float except valueerror print that ' not number except block is executed when the code in the try block throws an according exception afterwardsthe program continues normally unhandled exceptions force the program to exit handling different kinds of exceptionsexcept valueerror typeerror nameerror )built-in exceptionsmember of the helmholtz association slide
7,328
try input enter number number float except valueerror print that ' not number except zerodiv isionerror print you can ' divide by zero except print oops what ' happened several except statements for different exceptions last except can be used without specifying the kind of exceptioncatches all remaining exceptions carefulcan mask unintended programming errorsmember of the helmholtz association slide
7,329
else is executed if no exception occurred finally is executed in any case try open spam except ioerror print cannot open file else print read () close (finally print end of try member of the helmholtz association slide
7,330
access to exception objectsenvironmenterror ioerror oserror )exception object has attributes int str str otherwiseexception object is string spam_open py try open spam except ioerror as print errno filename strerror print python spam_open py spam no such file or directory errno no such file or directory spam member of the helmholtz association slide
7,331
draw(rectangle(line(exceptionfunction calls another function that function raises an exception is exception handlednopass exception to calling function member of the helmholtz association slide
7,332
passing exceptions ontry open spam except ioerror print problem while opening file raise raising exceptionsdef gauss_solver matrix )important code raise valueerror singular matrix member of the helmholtz association slide
7,333
exceptions are preferabledef square )if type =int or type =float return * else return none what about other numerical data types (complex numbersown data types)bettertry to compute the power and catch possible exceptionsduck-typing caller of function might forget to check return values for validity betterraise an exceptionmember of the helmholtz association slide
7,334
exceptions are preferabledef square )if type =int or type =float return * else return none def square )return * try result square value except typeerror print '{ 'invalid type format value )member of the helmholtz association slide
7,335
some objects offer context management which provides more convenient way to write try finally blockswith open test txt as for line in print line after the with block the file object is guaranteed to be closed properlyno matter what exceptions occurred within the block class method __enter__(selfwill be executed at the beginning and class method __exit__at the end of the context member of the helmholtz association slide
7,336
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,337
setunorderedno duplicated elements {" "" "" "alternative set([sequence]required for empty sets constant sets frozenset([sequence] empty setempty frozenset(subsets issubset(ts < strict subsets supersets issuperset(ts > strict supersets unions union(ts intersections intersection(ts differences difference(ts symmetric differences symmetric_difference(ts copys copy(as with sequencesthe following worksx in len(sfor in add(xs remove(xmember of the helmholtz association slide
7,338
other nameshashmapassociative array mapping of key value keys are unordered store spam eggs store eggs store bacon store eggs ' bacon ' spam ' iterating over dictionariesfor key in store print key store key ]compare two dictionariesstore =pool not allowed><member of the helmholtz association slide
7,339
delete an entrydel(store[key]delete all entriesstore clear(copystore copy(does it contain keykey in store get an entrystore get(key[default]remove and return entrystore pop(key[default]remove and return arbitrary entrystore popitem(member of the helmholtz association slide
7,340
delete an entrydel(store[key]delete all entriesstore clear(copystore copy(does it contain keykey in store get an entrystore get(key[default]remove and return entrystore pop(key[default]remove and return arbitrary entrystore popitem(views on dictionaries create viewitems(keys(and values(list of all (keyvaluetuplesstore items(list of all keysstore keys(list all valuesstore values(cautiondynamical since python member of the helmholtz association slide
7,341
python (staticpython (dynamicmdict = : : mdict ' ' ' ' mdict items (for in print ' ' mdict ' ]- mdict ' '- ' ' for in print ' ' mdict = : : mdict ' ' ' ' mdict items (for in print ' ' mdict ' ]- mdict ' '- ' ' for in print ' - ' member of the helmholtz association slide
7,342
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,343
so farprocedural programming data (valuesvariablesparametersfunctions taking data as parameters and returning results alternativegroup data and functions belonging together to form custom data types extensions of structures in /fortran member of the helmholtz association slide
7,344
my_point py class point pass point ( classcustom date type (herepoint objectinstance of class (herep attributes (here can be added dynamically hintpass is no operation (noopfunction member of the helmholtz association slide
7,345
my_point py class point def __init__ self )self self point ( print __init__ is called automatically after creating an object member of the helmholtz association slide
7,346
my_point py import math class point def __init__ self )self self def norm self ) math sqrt self ** self ** return point ( print norm ()method callautomatically sets the object as first parameter traditionally called self carefuloverloading of methods not possiblemember of the helmholtz association slide
7,347
default return value of strfor objects of custom classesp point ( print --print str )member of the helmholtz association slide
7,348
default return value of strfor objects of custom classesp point ( print --print str )this behaviour can be overwrittenmy_point py class point def __str__ self )return ({ { }format self self print ( member of the helmholtz association slide
7,349
default=checks for object identity of custom objects point ( point ( = false member of the helmholtz association slide
7,350
default=checks for object identity of custom objects point ( point ( = false this behaviour can be overwrittenmy_point py class point def __eq__ self other )return self =other and self =other = check for equal values true is check for identity false member of the helmholtz association slide
7,351
more relational operators__lt__(selfother<__le__(selfother!__ne__(selfother__gt__(selfother>__ge__(selfothernumeric operators__add__(selfother__sub__(selfother__mul__(selfothermember of the helmholtz association slide
7,352
classes can emulate built-in data typesnumbersarithmeticsint(myobjfloat(myobjfunctionsmyobjsequenceslen(myobjmyobjx in myobj iteratoresfor in myobj see documentationmember of the helmholtz association slide
7,353
have the same value for all instances of classmy_point py class point count count all point objects def __init__ self )point count + self __class__ count + point ( ) point ( count count point count member of the helmholtz association slide
7,354
spam py class spam spam don ' like spam @classmethod def cmethod cls )print cls spam @staticmethod def smethod ()print blah blah spam cmethod (spam smethod ( spam ( cmethod ( smethod (member of the helmholtz association slide
7,355
there are often classes that are very similar to each other inheritance allows forhierarchical class structure (is- -relationshipreusing of similar code exampledifferent types of phones phone mobile phone (is phone with additional functionalitysmart phone (is mobile phone with additional functionalitymember of the helmholtz association slide
7,356
class phone def call self )pass class mobilephone phone )def send_text self )pass mobilephone now inherits methods and attributes from phone mobilephone ( call (inherited from phone send_text (own method member of the helmholtz association slide
7,357
methods of the parent class can be overwritten in the child classclass mobilephone phone )def call self )self find_signal (phone call self member of the helmholtz association slide
7,358
classes can inherit from multiple parent classes examplesmartphone is mobile phone smartphone is camera class smartphone mobilephone camera )pass smartphone ( call (inherited from mobilephone take_photo (inherited from camera attributes are searched for in the following ordersmartphone mobilephone parent class of mobilephone (recursively)camera parent class of camera (recursivelymember of the helmholtz association slide
7,359
there are no private variables or private methods in python conventionmark attributes that shouldn' be accessed from outside with an underscore_foo to avoid name conflicts during inheritancenames of the form __foo are replaced with _classname__foo class spam __eggs _bacon beans dir spam _spam__eggs __doc__ __module__ _bacon beans 'member of the helmholtz association slide
7,360
the only class type until python in python default class new style classes unified class model (user-defined and build-indescriptores (gettersetterthe only class type in python available as basic class in python object member of the helmholtz association slide
7,361
if certain actions (checksconversionsare to be executed while accessing attributesuse getter and setterclass spam def __init__ self )self _value def get_value self )return self _value def set_value self value )if value < self _value else self _value value value property get_value set_value member of the helmholtz association slide
7,362
properties can be accessed like any other attributess spam ( value value value - value set_value ( get_value (set_value - get_value (getter and setter can be added later without changing the api access to _value still possible member of the helmholtz association slide
7,363
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,364
reminderfunctionsclasses and object thematically belonging together are grouped in modules import math math sin math pi import math as sin pi from math import pi as pi sin sin pi from math import sin pi online helpdir(mathhelp(mathmember of the helmholtz association slide
7,365
every python script can be imported as module my_module py ""my first module my_module py ""def add ( )""add and ""return print add ( )import my_module my_module add ( top level instructions are executed during importmember of the helmholtz association slide
7,366
if instructions should only be executed when running as scriptnot importing itmy_module py def add ( )return def main ()print add ( )if __name__ =__main__ main (useful for testing parts of the module member of the helmholtz association slide
7,367
modules can be grouped into hierarchically structured packages numeric packages are subdirectories __init__ py in each package directorylinalg __init__ py (may be empty__init__ py decomp py eig py solve py fft __init__ py member of the helmholtz association import numeric numeric foo (from __init__ py numeric linalg eig foo (from numeric linalg import eig eig foo (slide
7,368
modules are searched for in (see sys path )the directory of the running script directories in the environment variable pythonpath installation-dependent directories import sys sys path 'usr lib python zip 'usr lib python 'usr lib python plat linux member of the helmholtz association slide
7,369
,,batteries included"comprehensive standard library for various tasks member of the helmholtz association slide
7,370
constantse pi round up/downfloor(xceil(xexponential functionexp(xlogarithmlog( [base]log (xpower and square rootpow(xysqrt(xtrigonometric functionssin(xcos(xtan(xconversion degree radiantdegrees(xradians(ximport math math sin math pi - math cos math radians ( ) member of the helmholtz association slide
7,371
random integersrandint(abrandrange([start,stop[step]random floats (uniform distr )random(uniform(abother distibutionsexpovariate(lambdgammavariate(alphabetagauss(musigmarandom element of sequencechoice(seqseveral uniquerandom elements of sequencesample(populationkshuffled sequenceshuffle(seq[random]import random [ random shuffle [ random choice hello world ' member of the helmholtz association slide
7,372
classical time(functionality time class type is -tuple of int values struct_time time starts at epoch (for unix : : popular functionsseconds since epoch (as float)time time(convert time in seconds (floatto struct_time time localtime([seconds]if seconds is none the actual time is returned convert struct_time in seconds (float)time mktime(tconvert struct_time in formatted stringtime strftime(format[ ]suspend execution of current thread for secs secondstime sleep(secsmember of the helmholtz association slide
7,373
date and time objectsd datetime date ( datetime date ( dt datetime datetime ( datetime time ( calculating with date and timeprint delta print delta days print datetime timedelta days = )member of the helmholtz association slide
7,374
pathsabspath(pathbasename(pathnormpath(pathrealpath(pathconstruct pathsjoin(path [path []]split pathssplit(pathsplitext(pathfile informationisfile(pathisdir(pathislink(pathgetsize(pathexpand home directoryexpanduser(pathexpand environment variablesexpandvars(pathos path join spam eggs ham txt spam eggs ham txt os path splitext spam eggs py spam eggs py 'os path expanduser ~spam 'home rbreu spam os path expandvars mydir $test 'mydir test py member of the helmholtz association slide
7,375
working directorygetcwd(chdir(pathchanging file permissionschmod(pathmodechanging ownerchown(pathuidgidcreating directoriesmkdir(path[mode]makedirs(path[mode]removing filesremove(pathremovedirs(pathrenaming filesrename(srcdstrenames(oldnewlist of files in directorylistdir(pathfor myfile in os listdir mydir )os chmod os path join mydir myfile os path stat s_irgrp member of the helmholtz association slide
7,376
higher level operations on files and directories mighty wrapper functions for os module copying filescopyfile(srcdstcopy(srcdstrecursive copycopytree(srcdst[symlinks]recursive removalrmtree(path[ignore_errors[onerror]]recursive movemove(srcdstshutil copytree spam eggs beans symlinks true member of the helmholtz association slide
7,377
list of files in directory with unix-like extension of wildcardsglob(pathglob glob python / ]py python confitest py python basics py python curses_test py python curses_keys py python cmp py python button_test py python argument py python curses_test py 'member of the helmholtz association slide
7,378
simple execution of programp subprocess popen (ls - mydir ]returncode wait (wait for to end access to the program' outputp popen (ls stdout pipe stderr stdout wait (output stdout read (pipes between processes ls - grep txt popen (ls - stdout pipe popen (grep txt stdin stdout member of the helmholtz association slide
7,379
python program with standard command line option handlingargumentparser py - usage argumentparse py - filename example how to use argparse optional arguments - -help - filename -file filename - -verbosity show this help message and exit output file increase output verbosity python argumentparse py - newfile txt - newfile txt true member of the helmholtz association slide
7,380
simple list of parameterssys argv more convenient for handling several optionsargparse deprecated module optparse (since python argumentparse py parser argparse argumentparser description example how to use argparse 'parser add_argument - -file dest filename default out txt help output file parser add_argument - ,-verbosity action store_true help increase output verbosity args parser parse_args (print args filename print args verbosity member of the helmholtz association slide
7,381
csvcomma seperated values data tables in ascii format import/export by ms excel columns are delimited by predefined character (most often commaf open test csv reader csv reader for row in reader for item in row print item close ( open outfile writer csv writer writer writerow ([ ]member of the helmholtz association slide
7,382
handling different kinds of formats (dialects)csv reader csvfile dialect excel 'default csv writer csvfile dialect excel_tab 'specifying individual format parameterscsv reader csvfile delimiter further format parameterslineterminator quotechar skipinitialspace member of the helmholtz association slide
7,383
database in file or in memoryin python' stdlib since conn sqlite connect bla db conn cursor ( execute ""create table friends firstname text lastname text "" execute ""insert into friends values (jane doe """conn commit ( execute ""select from friends ""for row in print row close ()conn close (member of the helmholtz association slide
7,384
string formatting is insecure since it allows injection of arbitrary sql codenever do this symbol jane execute where firstname '{ format symbol )member of the helmholtz association slide
7,385
insteaduse the placeholder the database api providesc execute where name symbol friends (janis joplin bob dylan )for item in friends execute ""insert into friends values (,?""item python module cx_oracle to access oracle database web pagemember of the helmholtz association slide
7,386
xml-rpcremote procedure call uses xml via http independent of platform and programming language for the client use xmlrpc client import xmlrpc client xmlrpc client server http :/localhost : print list of available methods print system listmethods ()use methods print add ( , )print sub ( , )automatic type conversion for the standard data typesbooleanintegerfloatsstringstuplelistdictionarys (strings as keys)member of the helmholtz association slide
7,387
for the server use xmlrpc server from xmlrpc server import simplexmlrpcserver methods which are to be offered by the server class myfuncs def add self )return def sub self )return create and start the server server si mp lex ml rpcserver (localhost )server regist er_instance myfuncs ()server serve_forever (member of the helmholtz association slide
7,388
readline functionality for command line history and auto-completion tempfile generate temporary files and directories numpy numeric python package -dimensional arrays supports linear algebrafourier transform and random number capabilities part of the scipy stack mathplotlib plotting librarypart of the scipy stack member of the helmholtz association slide
7,389
introduction data types control statements functions input/output errors and exceptions data types ii object oriented programming modules and packages advanced techniques tools regular expressions (optionalsummary and outlook member of the helmholtz association slide
7,390
conditional assignment as if value < negative else positive can be realized in abbreviated form negative if value < else positive member of the helmholtz association slide
7,391
allows sequences to be build by sequences instead of using for [for in range ( ) append ** list comprehension can be useda ** for in range ( )conditional values in list comprehensiona ** for in range ( if ! since python set and dictionary comprehension * for in range ( ) * for in range ( )member of the helmholtz association slide
7,392
rememberattributes can be added to python objects at runtimeclass empty pass empty ( spam eggs also the attributes can be deleted at runtimedel spam member of the helmholtz association slide
7,393
attributes of an object can be accessed by name (string)import math getattr math sin print )sin empty (setattr ( spam print spam useful if depending on user or data input check if attribute is definedif not hasattr ( spam )setattr ( spam print spam member of the helmholtz association slide
7,394
also known as lambda expression and lambda form lambda ( lambda ** )( useful if only simple function is required as an parameter in function callfriends alice bob friends sort (friends bob alice 'friends sort key lambda upper ()friends alice bob 'member of the helmholtz association slide
7,395
def spam ( )print ( positional parameters can be created by listsargs [ spam (args keyword parameters can be created by dictionarieskwargs : spam (*kwargs member of the helmholtz association slide
7,396
def spam (args *kwargs )for in args print for in kwargs print ( kwargs ]spam ( = = member of the helmholtz association slide
7,397
global links the given name to global variabile static variable can be defined as an attribute of the function def myfunc ()global max_size if not hasattr myfunc _counter )myfunc _counter it doesn ' exist yet so initialize it myfunc _counter + print { call format myfunc _counter )print max size is { format max_size )max_size myfunc ( call max size is member of the helmholtz association slide
7,398
apply specific function on each list elementli [ mapli map math sqrt li mapli list mapli [ list map lambda li )[ functions with more than one parameter requires an additional list per parameterlist map math pow li [ ])[ member of the helmholtz association slide
7,399
similar to map but the result is filter objectwhich contains only list elementswhere the function returns true filter_example py li [ liodd filter lambda li print li li print liodd liodd print list liodd list liodd )python filter_example py li [ liodd list liodd [ member of the helmholtz association slide