-2

Why doesn't this very simple function work? I get NameError: name 'x' is not defined

def myfunc2():
    x=5
    return x

myfunc2()
print(x)

user3124200
  • 343
  • 1
  • 5

2 Answers2

1

You've declared and defined x inside of myfunc2 but not outside of it, so x is not defined outside of myfunc2.

If you'd like to access the value of x outside of myfunc2, you can do something like:

a = myfunc2()
print(a) # 5

I'd suggest reading up on variable scope in Python.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
  • 3
    I think to further clarify to a beginner this issue, one should change the names of variables. Otherwise, there's 2 different x's and the difference between the apparently 2 same things is confusing. Just my 2c. – Travis Griggs Jan 23 '19 at 19:22
-4

The x in myfunc2 is declared as a local. In order for this script to work, you can declare x as global:

def myfunc2():
    global x
    x = 5
    return x

myfunc2()
print(x)
>>>5

Hope this helps.