Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Local Variables in Python: Understanding Function-Level Scope | Understanding Variable Scope in Python
Intermediate Python

bookLocal 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.

123456
def greet(): message = "Aloha" print(message, "# local message") greet() print(message) # This line will result in an error
copy

The output is:

Aloha # local message
NameError: 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.

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 4. Luku 2

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Suggested prompts:

Can you explain what a global variable is?

Why does the error occur when trying to print 'message' outside the function?

Can you show an example of how to make 'message' accessible outside the function?

Awesome!

Completion rate improved to 3.7

bookLocal Variables in Python: Understanding Function-Level Scope

Pyyhkäise näyttääksesi valikon

A local variable is defined inside a function. You cannot access this variable outside the function's definition.

123456
def greet(): message = "Aloha" print(message, "# local message") greet() print(message) # This line will result in an error
copy

The output is:

Aloha # local message
NameError: 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.

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 4. Luku 2
some-alt