“Python mit Aussage lokalen Variablen” Code-Antworten

Python Lokale Variablen

'''Local variables are those that are defined in a block '''
a = 1 #This is NOT a local variable, this is a global variable
def add():
  b = 1 #This IS a local variable
  print(b)
add()
#If we tried to print(b) outside of the add() function, we would get an error
Determined Dragonfly

Python mit Aussage lokalen Variablen

A with statement does not create a scope (like if, for and while do not create a scope either).
As a result, Python will analyze the code and see that you made an assignment in the with statement, and thus that will make the variable local (to the real scope).
Tofufu

Python mit Anweisungsvariablen

a = 1
 
# Uses global because there is no local 'a'
def f():
    print('Inside f() : ', a)
 
# Variable 'a' is redefined as a local
def g():
    a = 2
    print('Inside g() : ', a)
 
# Uses global keyword to modify global 'a'
def h():
    global a
    a = 3
    print('Inside h() : ', a)
 
 
# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)
Tofufu

Ähnliche Antworten wie “Python mit Aussage lokalen Variablen”

Fragen ähnlich wie “Python mit Aussage lokalen Variablen”

Weitere verwandte Antworten zu “Python mit Aussage lokalen Variablen” auf Python

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen