• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Why local variables referenced before assignment?

Resolved: Why local variables referenced before assignment?

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I made the two functions below in Python 3. The first function test_list works fine with the list a without error. I can modify the list element in that function.
However, the second funciton test_int will pop an error local variable 'b' referenced before assignment. Why can’t I do this to the variable b?

Answer:

b += 1 is equivalent to b = b.__iadd__(1); since the name b gets bound by that statement (l.h.s.), the compiler infers that b is a local variable; however, the r.h.s. expression contains the name b as well and thus you get the error “local variable 'b' referenced before assignment” (the local name b doesn’t refer to anything at the time when the expression is evaluated).
a[0] = 2 on the other hand is equivalent to a.__setitem__(0, 2) and thus involves no name binding.
If you wish to modify a global name binding within a function, you can use the keyword global; there’s also the equivalent nonlocal for names contained in an outer, but not the global, scope.

If you have better answer, please add a comment about this, thank you!

python python-3.x
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: VBA – Applying border around the areas with value/text

01/04/2023

Resolved: How can I implement a function depending on picked up items?

01/04/2023

Resolved: Azuer Service Bus SDK not receiving the specified messages

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.