Basics

unicode characters

Foren

Python-Programme starten

ohne DOS-Fenster:
- *.pyw
- pythonw.exe

Setup

Magic Methods

Type hints (see documentation)

# For most types, just use the name of the type in the annotation
# Note that mypy can usually infer the type of a variable from its value,
# so technically these annotations are redundant
x: int = 1
x: float = 1.0
x: bool = True
x: str = "test"
x: bytes = b"test"

# For collections on Python 3.9+, the type of the collection item is in brackets
x: list[int] = [1]
x: set[int] = {6, 7}

# For mappings, we need the types of both keys and values
x: dict[str, float] = {"field": 2.0}  # Python 3.9+

# For tuples of fixed size, we specify the types of all the elements
x: tuple[int, str, float] = (3, "yes", 7.5)  # Python 3.9+

# For tuples of variable size, we use one type and ellipsis
x: tuple[int, ...] = (1, 2, 3)  # Python 3.9+

# On Python 3.8 and earlier, the name of the collection type is
# capitalized, and the type is imported from the 'typing' module
from typing import List, Set, Dict, Tuple
x: List[int] = [1]
x: Set[int] = {6, 7}
x: Dict[str, float] = {"field": 2.0}
x: Tuple[int, str, float] = (3, "yes", 7.5)
x: Tuple[int, ...] = (1, 2, 3)

from typing import Union, Optional

# On Python 3.10+, use the | operator when something could be one of a few types
x: list[int | str] = [3, 5, "test", "fun"]  # Python 3.10+
# On earlier versions, use Union
x: list[Union[int, str]] = [3, 5, "test", "fun"]

# Use Optional[X] for a value that could be None
# Optional[X] is the same as X | None or Union[X, None]
x: Optional[str] = "something" if some_condition() else None

Datentpyen

Build-in

offizielle Doku: vollständige Beschreibung

Strings

CheatSheet f-print

mystring = input()                  # Texteingabe
myint = int(mystring)               # Umwandlung String => Int
myfloat = float(mystring)           # Umwandlung String => Float
myint = int(mystring, 16)           # Umwandlung String => Hex
mystring = hex(myint)               # Umwandlung Int => Hex als String
mystring = bin(myint)               # Umwandlung Int => Bin als String
mystring = oct(myint)               # Umwandlung Int => Oct als String
myfloat = round(myfloat[,Stellen])
mystring = str1 + str2 + str3
mystring = string * myinteger       # Zeichenkette wird x-mal wiederholt
myint = len(mystring)               # Länge der Zeichenkette
mystring = chr(ASCII-Code)          # Umwandlung ASCII-Code (int) => Zeichen
myint = ord(Zeichen)                # Umwandlung Zeichen => ASCII-Code (int)
tab = chr(9)                        # für Spaltenwechsel in Excel
ord(u'p')                           # unicode "960"
unichr(960)                         # prints "p"
list("Hallo")                       # => ['H', 'a', 'l', 'l', 'o']
mystring.startswith("abc")          # => True, wenn mystring mit "abc" anfängt
mystring.endswith("abc")
", ".join(['A', 'B'])               # => 'A, B'
mystring.rjust(10)                  # mystring rechtsbündig ausgeben, insgesamt 10 Zeichen
mystring.ljust(10)                  # linksbündig
mystring.center(10)                 # zentriert
mystring.count(Zeichenkette)        # wie oft ist die Zeichenkette in mystring enthalten
mystring.find(Z-kette [,pos])       # an welcher Position ist die Zeichenkette in mystring enthalten (ab der Stelle pos); -1 wenn nicht
mystring.rfind(Zeichenkette)        # Suche beginnt rückwärts
mystring.replace(old, new)          # ersetzt die Zeichenkette old durch new; len(old) <> len(new) möglich!
mystring.startswith(Zeichenkette)   # => true/flase
mystring.endswith(Zeichenkette)     # => true/flase
mystring.partition(Trennzeichen)    # ergibt Tupel mit Zeichenkette vor Trennzeichen, dem Trennzeichen und Zeichenkette nach Trennzeichen
mystring.rpartition(Trennzeichen)   # wie .partition, beginnt rückwärts
mystring.split([Trennzeichen])      # zerlegt String in Liste ohne Trennzeichen, Trennzeichen Default ist Leerzeichen
":".join(["a", "b", "c"])           # => 'a:b:c' = Umkehrung von split
mystring[::-1]                      # String Rückwärts ausgeben/umdrehen

wenn das Ergebnis von .split() einen anderen Datentyp haben soll:

a = [int(n) for n in mystring.split()]

oder

a = map(int, mystring.split())

Slices

a = str(math.pi)
a[0] => 3               # 1. Zeichen, Zählung beginnt mit Null
a[-1] => 9              # letztes Zeichen
a[3:] => 4159265359     # ab dem 4. Zeichen bis zum Ende
a[:3] => 3.1            # nur die ersten 3 Zeichen
a[::2] => 3119639       # jedes zweite Zeichen
len(a) => 13            # Länge der Zeichenkette

posData = slice(3, 8)
„Beispieltext“[posData] # => „spiel“

Listen

mylist[index] = 'Element'                       # Element(e) ersetzen
del mylist[index]                               # Element löschen, Index oder Bereich möglich
mylist.insert(pos, 'Element')                   # Element einfügen
mylist.sort()                                   # in place
mylist.sort(key=str.casefold)                   # sort case in-sensitive
new_list = sorted(mylist)
mylist.reverse()                                # Reihenfolge umkehren
mylist.remove('Element')                        # Element löschen (geht auch .remove(pos)?)
mylist.append('Element')                        # am Ende anfügen
mylist.count('Element')                         # 'Häufigkeit 'Element' zählen
len(mylist)                                     # Anzahl aller Elemente
mylist.index('Element')                         # Position von "Element" in Liste
newlist = sorted(mylist, key = lambda i : i[1]) # sortiert nach 2. Subelement (Liste aus Listen)
transformed_list = list(zip(*mylist))           # swap columns and rows
flipped_list = [i for i in mylist[::-1]]        # flip list horizontally

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = [item for sublist in nested_list for item in sublist]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

Zahleneingabe

2j + 3      # komplexe Zahl
123         # dezimal
0xab        # hexadezimal
0b1010      # binär
0o23        # octal
<sehr langer Befehlsblock> \
<zweiter Teil in zweiter Zeile>

Dictionary

mydict = { "Peter":32, "Julia":29}
mydict["Peter"]                 # => 32
#del mydict("Peter")            # Eintrag löschen
Mydict.pop(„Peter“)             # löscht den Eintrag „Peter“
len(mydict)                     # Anzahl der Einträge
mydict.update({"Pia":18})       # neues Element hinzufügen
mydict.values()                 # Werte des Dicts: 32, 29
mydict.keys()                   # Schlüssel des Dicts: “Peter”, “Julia”
mydict.items()                  # Elemente des Dicts: („Peter“, 32), („Julia“, 29)
neu = mydict.copy()             # Kopie für Funktionen (arbeitet sonst mit Original-Liste!)
if mydict.has_key(„Peter“):     # ist True, da „Peter“ im Dict enthalten
for key, data in mydict.items():
    pass

Tupel

mytupel = (a, b, c)
mytupel = a, b, c               # Kurzschreibweise ohne Klammer
a, b, c = 1, 4, 7               # Zuweisung
mytupel = 1, 'Hallo', 3.2       # gemischte Zuweisung

Set

empty_set = {""}
my_set = set(["a", "b", "c"])                # convert list to set
another_set = {1, 2, 3}
all_together = my_set.union(another_set)     # = another_set.union(my_set)
intersec = my_set.intersection(another_set)  # = another_set.intersection(my_set)

Strukturen

Bedingungen

if <Bedingung 1> :          # if a < x < b : ist auch möglich!
    <Block A>               # oder pass, wenn Funktion noch implementiert wird
elif <Bedingung 2> :
    <Block B>
else:
    <Block C>

if 'a' [not] in 'Hallo' :   # prüft ob erse Zeichenkette in zweiter Zeichenkette enthalten ist

for-Schleife

for <Zähler> in <Iterable> :
    <Block A>
    if <Bedingung 1> :
        break               # Schleife komplett abbrechen
    if <Bedingung 2> :
        continue            # aktuellen Durchlauf abbrechen, mit nächstem Durchlauf weitermachen

while-Schleife

while <Bedingung> :
    <Block A>
    if <Bedingung> :
        break               # Schleife abbrechen

Fehler abfagen

try:
    <Block A>               # fehlerträchtige Stelle, z.B. Datei öffnen
except:
    <Block B>               # Fehlerbehandlung, z.B. Mitteilung an Benutzer

Funktionen

def <Funktionsname>([Parameter]):
    <Block A>               # Funktionscode
return <Wert>               # Rückgabewert, z.B. return None

def variable_args(*args, **kwargs):
    print(’args is’, args)
    print(’kwargs is’, kwargs)

variable_args(’one’, ’two’, x=1, y=2, z=3)
>>> args is (’one’, ’two’)
>>> kwargs is {’y’: 2, ’x’: 1, ’z’: 3}

Ergebnis = lambda Parameterliste : Ausdruck
mal = lambda x,y : x*y
a = mal(2,3)                # => a = 6

formatierte Ausgabe

print("{0} {1}").format(a, b)   # {0} wird durch a ersetzt, {1} durch b
{0:f}       => Anzeige float
{0:10.5f}   => Anzeige float, 10 Stellen insgesamt, 5 Nachkommastellen
{0:e}       => Anzeige Exponentialformat
{0:%}       => Anzeige Prozentformat
{0:d}       => Anzeige Dezimalzahl
{0:5d}      => Anzeige Dezimalzahl, 5 Ziffern
{0:05d}     => Anzeige Dezimalzahl, 5 Ziffern, führende Nullen werden ausgegeben
{0:b}       => Anzeige Binärzahl
{0:o}       => Anzeige Oktalzahl
{0:x}       => Anzeige Hexzahl

Testing/Debugging

assert os.path.isfile(infile), "Datei ungültig"

a = 5                               # ...input or change a here
assert a == 42                      # throws an AssertionError when a is not 42
assert a == 42, "Error message"     # throws an AssertionError
                                    # when a is not 42 with "Error message" for the message
                                    # the error message can be any expression

magic functions

def __init__(self)            # => Instanz erstellen
def __str__(self)             # Repräsentation für print(), immer str
def __repr__(self)            # 'technische' Repräsentation, z.B. um Objekt vonnständig zu beschreiben
def __add__(self, other)      # Addition von zwei Objekten
def __getitem__(self, key)    # Funktion self[key]
def __setitem__(self, key, val)
def __iter__(self)            # iteration =? for-loop
def __contains__(self, item)  # 'in' and 'not in'