FAQ: Introduction to Strings - Iterating through Strings

Thank you sir. That makes sense.

I didn’t realise it allows accessing a global variable, but not assigning to it - (within a function).

1 Like

There is a use case for accessing/assigning to a global but we need to declare a binding to that variable:

var = 0
def foo(x):
    global var
    var += x
    # ...

Now we can assign to var. This is a special case, not a norm, so only write this way when you can justify it.

The Codecademy answer:

def get_length(word):
return len(word)

From what I understand, there is no way to solve this problem using a function and a for loop and counter here.
If you want to solve with a for loop and counter you can do it without using a function, but it won’t let you continue in Codecademy.

word = “string”
n=0
for letter in word:
n+=1
print(n)
#prints 6

According to python website this problem is a lengthy topic, Programming FAQ — Python 3.11.0 documentation

and alot of conversation can be foudn on stack overflow, python - Why does this UnboundLocalError occur (closure)? - Stack Overflow

I think it works fine if you declare that variable before you use it in a calculation.

def get_length(string):
  n = 0  # variable is declared/defined & assigned here
  for char in string:
    n += 1
  return n

The function needs to return the variable, not print it to the console/screen.