Zum Inhalt

Gültigkeitsbereich & Schlüsselwörter

Geltungsbereich

Auf welche Variablen habe ich Zugriff - Lokaler Geltungsbereich → Innenfunktion. - Übergeordneter Bereich → einschließende Funktion. - Globaler Geltungsbereich → Modulebene. - Integrierter Bereich → Python-Integrationen (Summe, Max, Min usw.).

a = 1                   #global scope

def parent():
    a = 15              #parent scope
    def some_func():
        a = 10          #function scope or local scope
        return a
    return some_func

Schlüsselwörter

Globales Schlüsselwort

  • Ermöglicht das Ändern globaler Variablen innerhalb von Funktionen.
  • Für globalen Zugriff oder Geltungsbereich
total = 0
def counter():
    global total
    total += 1
    return total

counter()
counter()
print(counter())

(oder)

def counter1(total):
    total += 1
    return total

print(counter1(counter1(counter1(total))))

Nicht lokales Schlüsselwort

– Ermöglicht das Ändern übergeordneter Bereichsvariablen innerhalb verschachtelter Funktionen. - Für übergeordneten Zugriff oder Geltungsbereich

def outer():
    x = 'local'
    def inner():
        nonlocal x
        x = 'nonlocal'
        print('inner:', x)
    inner()
    print('outer:', x)
outer()