
i understand a variable created within a function can only be called inside that same function. i think that is correct. right?

once a variable is assigned inside a function, you can call it inside that same function as many times as you want. correct?

if the above two statements are correct, why does the following code not function correctly? or at least produce what i’m trying to produce. it produces something, just not what i’m looking for.
def append_sum(lst):
last_two_added = lst[2] + lst[1]
lst.append(last_two_added)
lst.append(last_two_added)
lst.append(last_two_added)
return lst
print(append_sum([1, 1, 2]))
this way works…
def append_sum(lst):
last_two_added = lst[2] + lst[1]
lst.append(last_two_added)
last_two_added = lst[2] + lst[1]
lst.append(last_two_added)
last_two_added = lst[2] + lst[1]
lst.append(last_two_added)
return lst
print(append_sum([1, 1, 2]))
this way works as well…
def append_sum(lst):
lst.append(lst[1] + lst[2])
lst.append(lst[1] + lst[2])
lst.append(lst[1] + lst[2])
return lst
print(append_sum([1, 1, 2]))
just wondering why i can’t assign the variable one time and call it for each of the appends. why do i have to assign it each time?
thanks!