Why it shows an unbounded local error | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why it shows an unbounded local error

https://code.sololearn.com/cnq4e2cha6UW/?ref=app

17th Sep 2019, 1:16 AM
Monish
1 Answer
+ 1
So the first thing that would be a good idea for the code is to properly indent because the code does tend to be sensitive to spacing. When the content in def add(): is indented to the same place as the function declaration line, it throws an indentation error. Aside from that, the main issue roots from the fact that the variable c is somehow not defined inside the method. This is because the variable can be accessed by the whole file but the variable does not have the right settings to be used by def add(). So, if we create an instance of that same variable c inside def add(), it can be used without an unbounded local error present. So, the solution to that is this: c=1 def add(): global c c=c+2 print(c) add() This way, def add() is being given global access to the variable, which in turn allows that variable to be used, keeping the original value the same. There is a more simple solution but with more repercussions. Another way to solve this issue can be done like this: c=1 def add(): c = 1 c=c+2 print(c) add() The only problem with this code is that we are reassigning the value of c, however, we only want to use the value of c and not change its original value. Technically in this code, it would work, but as you add more functions using the same variable, it can be a cumbersome task to deal with the variable constantly changing.
17th Sep 2019, 2:10 AM
Ankit Nakhawa
Ankit Nakhawa - avatar