Local Variables in Python: Understanding Function-Level Scope
A local variable is defined inside a function. You cannot access this variable outside the function's definition.
9
1
2
3
4
5
6
def greet():
message = "Aloha"
print(message, "# local message")
greet()
print(message) # This line will result in an error
123456def greet(): message = "Aloha" print(message, "# local message") greet() print(message) # This line will result in an error
The output is:
python912Aloha # local messageNameError: name 'message' is not defined
The message variable is not accessible in the global scope; it exists only inside the function. When the function exits, this variable ceases to exist.
Var alt klart?
Tak for dine kommentarer!
Sektion 4. Kapitel 2
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat