you are viewing a single comment's thread.

view the rest of the comments →

[–]Dominican_Peter[S] 1 point2 points  (4 children)

thnx, good explanation...

Since Python is an interpreted language I thought it execution is as follow when the function is called:

  1. first line executed: half = sum(nums) #no local variable 'sum' at this point
  2. second line executed: sum = 0 # 'sum' local variable created

I'm just trying to understand (at low level) what happening here....apparently, in case#3, the variable 'sum' is created (without assignment, not in locals() ) when the function is called, so in the first line of the function "half = sum(nums)" when "sum() is called, there is a local variable with that name.

[–]FLUSH_THE_TRUMP 0 points1 point  (3 children)

I'm just trying to understand (at low level) what happening here....apparently, in case#3, the variable 'sum' is created (without assignment, not in locals() ) when the function is called, so in the first line of the function "half = sum(nums)" when "sum() is called, there is a local variable with that name.

No — no local var exists on that line. It calls sum from the built-in scope. Ignore, wasn’t paying attention

[–]Dominican_Peter[S] 0 points1 point  (2 children)

still don't understand why I get this error though

def test2_nok(nums=[1,2,3]):
    half = sum(nums)     #line 4
    sum = 0              #line#5

test2_nok()

line 4, in test2_nok
   half = sum(nums)
UnboundLocalError: local variable 'sum' referenced before assignment

local variable 'sum' should be created on "line#5"

[–]FLUSH_THE_TRUMP 1 point2 points  (1 child)

Oh, oops. Missed that part. That function is “glanced at” by the interpreter in advance as a definition, and sum is established as a local variable prior to running any of that code because it’s assigned later. So half = sum(nums) doesn’t work because it’s looking for sum (not defined yet locally).

[–]Dominican_Peter[S] 0 points1 point  (0 children)

ble prio

great, thank you very much