[Tutor] exec('a=1') in functions
Jan Kenin
jankenin at gmx.de
Tue Aug 17 12:37:22 EDT 2021
Hello,
in python 2.7 the following code works:
>>> def f( b ):
... exec( 'a=%s'%b )
... print 'a=', a
...
>>> f( 1 )
a= 1
in python3.6 this works in the interpreter:
>>> b=1
>>> exec('a=%s'%b)
>>> a
1
but not in a function:
>>> def f( b ):
... exec( 'a=%s'%b )
... print( 'a=', a )
...
>>> f( 1 )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in f
NameError: name 'a' is not defined
How can I get the latter working?
Thanks for all advice!
Jan
More information about the Tutor
mailing list