Key Points:
-
Local Scope of name
- The variable name is defined inside the function set_name().
- This means name exists only within the function's scope and cannot be accessed outside.
-
Function Execution (set_name())
- The function runs and assigns 'Python' to name, but since name is local, it is lost after the function finishes execution.
-
Error in print(name)
- The print(name) statement is outside the function and cannot access name because name only exists inside set_name().
- Result: Python will throw a NameError: name 'name' is not defined.
How to Fix It?
If you want name to be accessible outside the function, you can:
Solution 1: Return the value
Solution 2: Use a Global Variable (Not Recommended)
- This works but using global is not recommended unless absolutely necessary, as it can lead to unexpected behavior.
0 Comments:
Post a Comment