Using variables that are defined outside of a function inside a function

So I was practicing some of the python I’ve learned and came across this problem. I can’t use a variable I’ve defined outside of a function, inside a function? Here is my example.

counter = 0
str = "apple"

def count1(word):
  for letter in word:
    if letter != "p":
      continue
    else:
      counter += 1
  return counter

count1(str)

That is assignment. The global variable counter is read-only. To be able to assign to that variable, tell your function to institute that binding.

var = 0
def foo(bar):
  global var

If we are mutating the global variable what need have we of the return?

So this brings us to the curtailment of interacting with globals in our functions. The return value is the way to address this. Let the calling scope deal with the return value.

def foo(bar):
  var = bar + bar
  return var
bar = foo('bar')
print (bar)    #  barbar
2 Likes

Ok I think I understand, so what your saying is if I want to use a variable that is defined globally (or not inside of a function) I would have to let my function know by using the keyword global. However if I do this there’s no point in using the return because the value would already be stored in the global variable, which I could then use or print.

2 Likes