====== Python-Workshop -- Transkript Syntax ====== # Ausgabe print("Hello World") # Bloecke mittels Whitespace if True: print("A") print("B") print("C") # Auf andere Module zugreifen import string print(string.ascii_letters) # Variablennamen variable = 1 variable2 = 2 var_Var = 3 # nicht: 2variable # interne Variablen mit Unterstrich _variable = 4 # Standardtypen: int, float, bool, str, None number = 1 num = int("12") fract = 1.2 mybool = True otherbool = False and False mystr = "München \"Hallo\"" otherstiring = 'oasenu"oänuth' longstring = """Eine Geschichte mit Zeilenumbrüchen.""" var = None # Listen mylist = [1, 2, "orceuh", None, False] # Länge print(len(mylist)) # Zugriff print(mylist[0]) print(mylist[1]) print(mylist[-1]) # Zuweisungen mylist[2] = "krcho" mylist.append("krcoh") # Mitgliedschaftstest für Iterables print(None in mylist) # True print(mylist.index(None)) # 3 print(42 in mylist) # False # Tupel (unveränderliche Listen) mytupel = ( 1, 2, None, False, "string", ) # einelementige oneelementtupel = (1,) # dict mydict = {'a' : 1, 'b' : 3, 'x' : 3} print(mydict['a']) # kann Fehler produzieren print(mydict.get('d')) # None mydict['b'] = 5 mydict['e'] = 7 # Kontrollfluss # if mybool = True if mybool: print("true") elif mybool is None: print("none") else: print("False") myint = 8 if myint == 10: print("zehn") emptylist = [] if emptylist: print("oh no") else: print("yes") # Konvertierung nach False: [], {}, None, "", 0, ... # for Schleifen mylist = [1, 2, "orceuh", None, False] for i in mylist: print(i) # in dicts wird ueber Schluessel iteriert mydict = {'a' : 1, 'b' : 3, 'x' : 3} for key in mydict: print(mydict[key]) # Zahlenbereich for n in range(10): if n % 2: continue print(n) # while-Schleife condition = True while True: if condition: break mystring = "sonehu" while mystring: print(mystring) mystring = mystring[:-1] myarray = [0, 1, 2, 3] print(myarray[1:2]) # [1] # Funktionen def myfun(n): if not n: return 1 return n*myfun(n-1) # optionale Parameter / Defaultwerte def hello(mystr="World"): print("Hello {}".format(mystr)) hello() # Hello World hello("World") # Hello World hello("Krautspace") # Hello Krautspace # Keyword-Parameter hello(mystr="Krautspace") # Hello Krautspace # Klassen class MyClass: def __init__(self): self.counter = 42 def print_counter(self): print(self.counter) # Don't do this at home # setter und getter sind nicht pythonic # Stichwort @property def set_counter(self, new_value): self.counter = new_value instance = MyClass() instance.print_counter() print(instance.counter) # Vererbung class SecondClass(MyClass, object): pass # list comprehension mylist = [1, 2, "orceuh", None, False] boxedlist = [[val] for val in mylist] truelist = [val for val in mylist if val]