1

In my following code I have the following lines of coding repeated in my code so am trying to insert them inside a function and call them whenever they are needed, but there is an error happening and I don't know why:

list1=[1000,2000,3000,4000,5000]
i=0
c=0.5
n=1000
def func(list1,i,c,n):
    x=list1[i]/2
    y=x*c
    z=n-y
    if z<=0:
        list1.pop(i)
func(list1,i,c,n)
print('x=',x,'y=',y,'z=',z)

When i try to execute the code I get an error that x or y or z are not defined.

1 Answer 1

1

Variables creates inside functions only exist until the function ends. If you want the x,y and z to be available from the global scope, you will need to declare you'd like this behaviour. You can indicate that a variable will be global by simply adding this line at the beginning of the function:

def func(new_x):
    global x
    x = new_x

func(5)
print('x=', x)

This will print 5 for example. You can declare global for multiple variables at once by using comma like so:

def func(new_x):
    global x, y
    x = new_x
    y = new_x+1

func(5)
print(f'x={x} y={y}')

This will print x=5 y=6. Notice the way I used to format the string. It's called f-string and you can read about it here.

Sign up to request clarification or add additional context in comments.

4 Comments

but can you tell me how to exactly fix my posted code ? how to make it work
add global x,y,z at the beginning of you function.
you r rock sir !
I would like it if you could mark my answer as correct please. I'd really appreciate that :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.