OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Variables declared outside function

  • Thread starter Thread starter Bogdan
  • Start date Start date
B

Bogdan

Guest
I was just trying to see how variable scopes work and ran into the following situation (all ran from the terminal):

Code:
x = 1
def inc():
    x += 5

inc()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in inc
UnboundLocalError: local variable 'x' referenced before assignment

I was thinking maybe I don't have access to x in my method, so I tried:

Code:
def inc():
    print(x)

1

So this works. Now I know I could just do:

Code:
 def inc():
     global x
     x += 1

And this would work, but my question is why does the first example fail? I mean I would expect since print(x) worked that x is visible inside the function so why would the x += 5 fail?
<p>I was just trying to see how variable scopes work and ran into the following situation (all ran from the terminal):</p>
<pre><code>x = 1
def inc():
x += 5

inc()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in inc
UnboundLocalError: local variable 'x' referenced before assignment
</code></pre>
<p>I was thinking maybe I don't have access to x in my method, so I tried:</p>
<pre><code>def inc():
print(x)

1
</code></pre>
<p>So this works. Now I know I could just do:</p>
<pre><code> def inc():
global x
x += 1
</code></pre>
<p>And this would work, but my question is why does the first example fail? I mean I would expect since <code>print(x)</code> worked that <code>x</code> is visible inside the function so why would the <code>x += 5</code> fail?</p>
 

Latest posts

Top