What happens if you try to access a local variable outside the function where it is defined?

QuestionsQuestions8 SkillsProShell FunctionsNov, 25 2025
0170

If you try to access a local variable outside the function where it is defined, you will encounter a NameError. This is because local variables are only accessible within the scope of the function in which they are defined.

Here's an example:

def greet(name):
    message = "Hello, " + name + "!"
    print(message)

greet("John")  # Output: "Hello, John!"
print(message)  # This will raise a NameError

In this example, the message variable is defined inside the greet function, making it a local variable. Attempting to print message outside the function results in a NameError because message is not defined in that scope.

0 Comments

no data
Be the first to share your comment!