Return Indentation Differences

Hello!

I am curious as to what would occur differently in the code below when return is executed at either level on indentation. I am having trouble determining where to place return when writing my functions and would love some clarification on this topic! Thanks in advance :wink:

Situation A:

word = 'Hello'

def get_length(string):
---count = 0 
---for letter in string:
------count += 1
------return count 

vs

def get_length(string):
---count = 0 
---for letter in string:
------count += 1
---return count 

  1. What is happening that is different when return is indented by 6 dashes (-) vs only 3 dashes and why?
  2. Also, originally I had `count = 0’ defined outside of the function but received an error. Why does it need to be in the function to execute properly?

The indent decides what part of the function the return it executing from. So for the ------ one, it’s returning on the first run of the for loop, so you would expect it to only return 1. However when the return is on the --- one, it’s returning after the for loop has completed, and so should correctly return the length of the string. The indent defines which part of the function it is running in (assuming there’s things that require indents i.e. loops, if statements).

For count, a functions scope is confined to itself and can only use variables which are defined within its scope or received as arguments for parameters. This way you don’t need to know the names of all the variables used within the code to avoid name pollution. If it didn’t work this way, then the count variable in the function could override a count variable you are using in another program which accesses the function.

1 Like

Thank you! I think this clears things up. My only remaining question would be why count when defined outside of the function would not be considered a global variable in this situation?

It is a global variable, however you cannot edit global variables inside of a function due to the reasons I mentioned above. If you printed the value you would see that the count defined outside would carry in, but you cannot edit it.