0

I'm very new to coding and am having trouble with functions. What is wrong with this and how can I do this properly?

x = 0
def function():
    x = x + 1
    return(x)
x = 2
x = function()
print(x)

2 Answers2

0

Change the function to this if you want to assign variable located outside the function:

def function():
    global x
    x = x + 1
    return x
Nhiên Ngô Đình
  • 544
  • 2
  • 6
  • 16
0

If you modify (bind) a variable anywhere in a function, it's considered to be local everywhere in that function unless explicitly declared global or nonlocal(a). This is covered by the Python execution model:

If a name is bound in a block, it is a local variable of that block, unless ...

In other words, what you have is effectively:

x = 0
def function():
    local_x = local_x + 1 # use of unitialised local_x
    return(local_x)

That means you need something like:

x = 0
def function():
    global x
    x = x + 1 # use of initialised x
    return(x)

However, keep in mind that global variables are mostly the wrong way to do things. They're probably okay for small programs but can become a nightmare when you get to a certain complexity level.

One method to do this is to just pass in the variable and pass back the modified value, re-assigning it in the caller:

def function(value):
    return value + 1

def caller():
    non_global_x = function(non_global_x)

Note that non_global_x may still be a global in that case but it can be also any other suitable variable, such as the member of an object.


(a) The difference between these two is that global means global, meaning it will be available everywhere. Non-local variables simply refer to ones somewhere up the hierarchy, but you may find them before you get to global scope (often used in nested functions).

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Hey, thanks for the detailed answer, but would you mind giving me an example of an alternative to global variables, but still using functions? – HideousPillow Jul 24 '20 at 17:06