0

I wanted to use a string in global scope inside a function. I read somewhere that different scopes have different values for their respective local variables even if they have the same name.

But in my case, I am getting something like this

https://i.stack.imgur.com/hyqZk.png (this link contains the image)

AMT
  • 11
  • 3
  • 2
    Possible duplicate of [Global Variable in Python](https://stackoverflow.com/questions/8883000/global-variable-in-python) – Sraw Sep 20 '17 at 01:24
  • Also relevant - https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules – Andrew Guy Sep 20 '17 at 01:25
  • 2
    First, please post code *as formatted text*. Do **not** post links to images of code. Second, in your example, the variable *is defined globally* so I don't really understand your question. – juanpa.arrivillaga Sep 20 '17 at 01:25
  • 1
    I would suggest going and doing some research on Python scoping rules. There are plenty of questions on this site that cover what you are asking. You can always come back with a question if you can't find the answer from an existing question. – Andrew Guy Sep 20 '17 at 01:28

2 Answers2

0

From the Python FAQ:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

So the printscr function can see the variable in the global scope, but if you try to modify the value of string, you get an UnboundLocalError because the name doesn't exist in the local scope and you may not modify the global variable from inside the function.

def printscr():
    # No local name `string` exists and can't assign to the global variable.
    string += 2
Community
  • 1
  • 1
skrx
  • 19,980
  • 5
  • 34
  • 48
0

Have a look at code below

def printstr():
    print string

string = 1
printstr() 

output

1

However if you try to update the value in the function, that will exist only in local scope

def printstr():
    string =+ 1
    print string

string = 1
printstr()
print string

output

2

1

so string outside printstr still holds 1

to update value globally

def printstr():
    global string
    string =+ 1
    print string

string = 1
printstr()
print string

output

2

2

We have to use global keyword to refer the global scoped variable, I hope this clarifies your doubt