How to declare a variable from a scope?

How to make the code as follows? I want to reference a variable for assignment in the application area.

def outer():
    x = 0

    def inner():
        x += 1

    inner()

The code, as written, is given UnboundLocalError. I understand why I get this error, I just don’t know how I indicate what xcomes from the transfer area.

+4
source share
2 answers

You cannot do what you ask in a clean way. Nothing like a statement globalthat can help you. You need to encode it like this:

def outer():
    x = 0

    def inner(x):
        return x + 1

    x = inner(x)

This has the added benefit of explicitly indicating how data is transferred and exited from the function.

, x , .

+1

:

def outer():
    x = [0]

    def inner():
        x[0] += 1

    inner()

, .

+1

Source: https://habr.com/ru/post/1531119/


All Articles