Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discrepancy in using global variable in a function in Python

Tags:

python

I was just playing around with Python and I came across something interesting which I didn't quite understand. The code goes as follows:

a = 1
def function():
  print(a)
function()
print(a)

Here, a is a global variable and I used it in my function and the result was:

1
1

I was able to use a global variable locally in my function without having to use global a in my function.

Then, I experimented further with this:

a = 1
def function():
  a = a+1
  print(a)
function()
print(a)

When I ran this code, an error showed up and it said that the local variable a was referenced before assignment. I don't understand how before it recognized that a was a global variable without global a but now I need global a like this

a = 1
def function():
  global a
  a = a+1
  print(a)
function()
print(a)

in order for this code to work. Can someone explain this discrepancy?

like image 208
Aditya Shivapooja Avatar asked Sep 20 '26 02:09

Aditya Shivapooja


1 Answers

You can read the value from a global variable anytime, but the global keyword allows you to change its value.

This is because when you try and set the a variable in your function, by default it will create a new local function variable named a. In order to tell python you want to update the global variable instead, you need to use the global keyword.

like image 138
Daniel Geffen Avatar answered Sep 22 '26 15:09

Daniel Geffen