I just started self teaching Python, and I need a little help with this script:
old_string = "didnt work" new_string = "worked" def function(): exec("old_string = new_string") print(old_string) function()
I want to get it so old_string = "worked"
.
Global variables can be used by everyone, both inside of functions and outside.
The exec command is a powerful tool for manipulating file-descriptors (FD), creating output and error logging within scripts with a minimal change. In Linux, by default, file descriptor 0 is stdin (the standard input), 1 is stdout (the standard output), and 2 is stderr (the standard error).
exec() in Python. exec() function is used for the dynamic execution of Python program which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed.
Python exec() does not return a value; instead, it returns None. A string is parsed as Python statements, which are then executed and checked for any syntax errors. If there are no syntax errors, the parsed string is executed. If it's an object code, then it is simply executed.
You're almost there. You're trying to modify a global variable so you have to add the global
statement:
old_string = "didn't work" new_string = "worked" def function(): exec("global old_string; old_string = new_string") print(old_string) function()
If you run the following version, you'll see what happened in your version:
old_string = "didn't work" new_string = "worked" def function(): _locals = locals() exec("old_string = new_string", globals(), _locals) print(old_string) print(_locals) function()
output:
didn't work {'old_string': 'worked'}
The way you ran it, you ended up trying to modify the function's local variables in exec
, which is basically undefined behavior. See the warning in the exec
docs:
Note: The default locals act as described for function
locals()
below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after functionexec()
returns.
and the related warning on locals()
:
Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With