Câu hỏi phỏng vấn Python
Câu hỏi

What are the rules for local and global variables in Python?

Câu trả lời

In Python, the rules for local and global variables are distinct and are crucial for managing the scope and accessibility of variables within a program. Here's a detailed explanation of these rules:

Local Variables

Local variables are those that are defined within a function and are only accessible within that function's scope. They cannot be accessed outside of the function in which they are declared. This means that any variable created inside a function is local to that function unless explicitly declared otherwise.

  • Creation: A variable is considered local if it is assigned a value within the body of a function.
  • Accessibility: Local variables can only be accessed within the function where they are defined. Attempting to access them outside the function will result in a NameError[3][4][11].
  • Lifetime: The lifetime of a local variable spans the execution of the function. The variable is created when the function is called and is destroyed once the function execution is complete.

Global Variables

Global variables are defined outside any function and can be accessed from any part of the program, including inside functions. They are useful when multiple functions need to access the same data.

  • Creation: A variable is considered global if it is defined at the top level of a script or module, outside of any functions[5][6].
  • Accessibility: Global variables can be accessed both inside and outside of functions. If a global variable is accessed within a function, it can be read without any additional declarations. However, if you want to modify a global variable within a function, you must declare it as global using the global keyword[1][5][9].
  • Lifetime: The lifetime of a global variable extends throughout the execution of the program. It is created when its declaration is executed and is destroyed when the program terminates.

Using the global Keyword

To modify a global variable within a function, you must firs...

junior

junior

Gợi ý câu hỏi phỏng vấn

middle

How can I create a copy of an object in Python?

senior

Why are Python's private methods not actually private?

senior

What is the difference between a function decorated with @staticmethod and one decorated with
@classmethod ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào