-1

Why this function is not resetting x?

My code looks like below:

def reset():
    x=0

x = 22
reset()
print(x)

Expected result x = 0, actual result x = 22

meowgoesthedog
  • 14,670
  • 4
  • 27
  • 40
eljukar
  • 3
  • 1
  • 2
    Possible duplicate of [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – Faboor May 17 '19 at 10:11

2 Answers2

0

You need to have x as global:

def reset():
  global x
  x = 0
Faboor
  • 1,365
  • 2
  • 10
  • 23
0

You need learn more about scope in Python.Assignments to names always go into the innermost scope.The global statement can be used to indicate that particular variables live in the global scope and should be rebound there; the nonlocal statement indicates that particular variables live in an enclosing scope and should be rebound there.

def scope_test():
    def reset_local():
        x = "local"

    def reset_nonlocal():
        nonlocal x
        x = "nonlocal"

    def do_global():
        global x
        x = "global"

    x = "origin"
    reset_local()
    print("After local assignment:", x)
    reset_nonlocal()
    print("After nonlocal assignment:", x)
    reset_global()
    print("After global assignment:", x)

scope_test()
print("In global scope:", x)

output:

After local assignment: origin
After nonlocal assignment: nonlocal
After global assignment: nonlocal
In global scope: global

Note how the local assignment (which is default) didn’t change scope_test’s binding of x. The nonlocal assignment changed scope_test’s binding of x, and the global assignment changed the module-level binding.

You can also see that there was no previous binding for x before the global assignment.

You can consult Python tutorial for more infomation:https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces. Hope help you more or less

Plutors
  • 72
  • 1
  • 9