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

Explain the UnboundLocalError exception and how to avoid it?

Câu trả lời

The UnboundLocalError in Python is an exception that is raised when a local variable is referenced before it has been assigned a value within a function or method. This error typically occurs when trying to modify or access a variable within a function's local scope before it has been properly initialized or when there is a conflict between local and global variables with the same name.

To avoid an UnboundLocalError, you should ensure that variables are initialized before they are used within a function. If you intend to use a global variable within a function and modify it, you must declare it as global using the global keyword. This tells Python that the variable should be fetched from the global scope rather than treating it as a local variable.

Here's an example of code that would cause an UnboundLocalError:

x = 10

def increment():
    x += 1  # Trying to increment the global variable x without declaring it as global
    print(x)

increment()

This code will raise an UnboundLocalError because x is being modified within the function increment without being declared as a global variable. Python assumes x is a local variable due to the assignment, but it hasn't been initialized within the function's scope.

To fix this error, you can use the global keyword:

x = 10

def increment():
    global x  # Declaring that x is a global variable
    x += 1
    print(x)

increment()

Now, Python knows to use the global variable x, and the code will work as expected.

Another way to avoid this error is to pass the variable as an argument to the function and return the modified value. This is a common practice to avoid side effects and make functions easier to understand and test.

x = 10

def increment(va...
middle

middle

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

senior

How is set() implemented internally?

senior

What's the difference between a Python module and a Python package?

senior

Why Python (CPython and others) uses the GIL?

Bình luận

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

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