Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

It seems that assigned variables do not go from outside a defined function to inside a defined function, or vis-versa

In the code

def add(nums):

    a = 0

    for num in nums:

        a = num + a

    print(a)

add([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

the variable a will print just fine, however if I bring the print command out of add() {all the way to the left} then python acts like 'a' has not been assigned a value and flips out. Surely there has to be a work around for this right?

4 Answers

The variable 'a' is a local variable of 'add' method - so, the scope where you are able to access it is limited by the scope of 'add' method - thus you cannot access this variable from the outside of the method's scope.

Below you can find one of the workarounds for your problem. The idea is that you have to return a value of the local variable to the outer scope, and after that you will be able to access it. Also it should be noticed that I intentionally gave different names ('result' and 'sum') to different variables with the same semantics - for the sake of making it clearer to see that those variables are completely different in terms of their accessibility scope:

def add(nums):
  result = 0
  for num in nums:
    result += num
  return result

sum = add([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(sum)

That seems wired, is it like that so there can be multiple variable "a's" in a single code, just all localized to their own functions?

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Trust me, you want scope :)

Everything belongs to the scope it was defined in. If it was defined in the script, it belongs to the script's scope which is called global. If it was defined in a function, it belongs to the function. If they didn't belong to their scope, they'd bleed through. Imagine this:

my_nums = [1, 2, 3]

def my_function(nums):
    my_nums = []
    for num in nums:
        my_nums.append(num*2)

If we don't have scope, and I call my_function(my_nums), now the my_nums on the outside is replaced with [2, 4, 6] with no indication of that from my function or anything else. That's just messy.

I see, this exists to help the programmer keep variables organized. That makes sense. Thanks Kenneth and Roman!