1

I have the following loop structure and also the problem, that it is not possible to increment a variable inside of this code due to UnboundLocalError:

while True:
    def function_1():
        def function_2():
            x += 1
            print(x)
        function_2()
    function_1()

My solution was now this one:

x = 0
while True:
    def function_1():
        def function_2():
            global x
            x += 1
            print(x)
        function_2()
    function_1()

Is there another solution without global?

2 Answers 2

1

use a mutable value.

x = []
x.append(0)
while True:
    def function_1():
        def function_2():
            x[0]= x[0]+1
            print x[0]
        function_2()
    function_1()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I will test which one is faster.
1

Pass and return x to all the functions.

x = 0
while True:
    def function_1(x1):
        def function_2(x2):
            x2 += 1
            print(x2)
            return x2
        return function_2(x1)
    x = function_1(x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.