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

What are local variables and global variables in Python?

Câu trả lời

In Python, variables can be classified as either local or global based on their scope, that is, the region of the program where they can be accessed and modified.

Local Variables

Local variables are defined within a function and their scope is limited to that function itself. This means they can only be accessed and manipulated within the function in which they are declared. Once the function execution is completed, these local variables are destroyed. For example, if you define a variable x inside a function func(), you cannot access x outside of func() without causing an error[2][3][4].

Global Variables

Global variables, on the other hand, are defined outside any function, typically at the top level of the Python script. These variables have a global scope, which means they can be accessed and modified from anywhere in the program, whether inside functions or outside. If you declare a variable x at the top level of your script, it can be accessed within any function or block within that script. To modify a global variable inside a function, you must declare it as global within the function to avoid Python treating it as a local variable[3][4][6].

Examples and Usage

Here's a simple example to illustrate the use of local and global variables:

junior

junior

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

middle

What's the difference between lists and tuples ?

expert

Why isn't all memory freed when Python exits?

middle

What is a Callable?

Bình luận

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

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