2

When I run this code I don't get a error. I'm trying to calculate l1 and put into variable a.

m=np.linspace(-np.pi,np.pi,1000)
l1="np.sin(m)"
exec(f"a ={l1}")
print(a)

When I run this I get a error.Why?

def g():
    m=np.linspace(-np.pi,np.pi,1000)
    l1="np.sin(m)"
    exec(f"a ={l1}")
    print(a)
g()

Error:name "a" is not defined

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

2

Check link: Setting variables with exec inside a function

def g():
    m=np.linspace(-np.pi,np.pi,1000)
    l1="np.sin(m)"
    exec(f"global a; a={l1}")
    print(a)
g()
manzt
  • 454
  • 2
  • 12