0
votes

I have declared global variables that i need to access and modify in a function in a class. This function loops indefinitely once called and stream data passes through it. I need to be able to use x y z variables inside the function, and redefine their values as stream_data comes through. My current code looks like this:

x = 10
y = 8
z = 2
class Program():
    def function(stream_data):
        while True:
            try:               
                a = stream_data['data']
                if (a - z) > y:
                    y = a - z
                else:
                    pass
            except:
                continue

I get error "local variable y defined in enclosing scope on line 7 referenced before assignment". How can I format this code so that when the function is first called, it uses the global variables, and then on each subsequent calling it uses the variable y it redefined? Thanks I am new to coding and really need help!

1
Check out Global, Local and nonlocal Variables to understand how Python considers Global and Local variables. - DarrylG

1 Answers

0
votes

Use

global x, y, z to use the global variables

Like This-

x = 10
y = 8
z = 2
class Program():
    def function(stream_data):
        while True:
            try:
                global x,y,z
                a = stream_data['data']
                if (a - z) > y:
                    y = a - z
                else:
                    pass
            except:
                continue

Alternatively, you can also initialize x,y,z within your function.

Let me know if this helps!