-1

Sorry for the beginner question. In the below code, the output I'm getting is "Original" and not "Function". Doesn't the value of name change after passing through the function? Thanks

global name
name = "Original"

def test():
    name = "Function"

test()
print(name)
Rohan Pinto
  • 51
  • 1
  • 5
  • No, it doesn't. `name` in `test` is a *local variable*, as is always the default when you assign to a variable in python. You need to use the `global` statement *in the `test` function if you want that to change*. Note, `global name` in the global scope does absolutely nothing, *any assignment in the global scope will be global already* – juanpa.arrivillaga Jun 01 '21 at 16:49
  • As an aside, you *really* shouldn't be using mutable, global state like that anyway – juanpa.arrivillaga Jun 01 '21 at 16:50
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). Stack Overflow is not intended to replace existing documentation and tutorials. – Prune Jun 01 '21 at 16:52

3 Answers3

1

Use the global keyword in the function.

name = "Original" # define name

def test(): # define our function
    global name # this function can now change name
    name = "Function" # change the value

test() # run the function
print(name) # returns Function

I'd assume global needs to be in the function so you could do something like this, where a function can use text without effecting the text var:

text = "Original"

def test():
    global text
    text = "Function"

def printText(text):
    textToPrint = text # use text var without any issues in this function
    print(textToPrint)

test()
print(text)
UCYT5040
  • 367
  • 3
  • 15
0

global declarations go inside the function you want to apply them to, not at the top-level.

name = "Original"

def test():
    global name
    name = "Function"

test()
print(name)
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
0
    name = "Original" #global variable
    
    
    def test():
        #to update the global value you have to declare it here
        global name
        name = "Function"
    
    test()
    print(name)

you can read more about it here, https://www.programiz.com/python-programming/global-keyword