简体   繁体   中英

assining variables in a function with exec, python

my problem is, that i assign a variable and want to use it later:

name_list = ["a", "b","c"]


for x in range (len(name_list) -1):
    exec (name_list[x] + str (x) + "= 0" ) 
    
    print ( name_list[x] + str (x) )

Output:

a0
b1

If i use:

print (a0)

outside the function, the code analysis will throw an error, because the variable is not assigned yet, but the output is: 0

If you run exec inside a function, you should use global keyword to get variable visible outside the function. Like this:

def test(a):
    exec(f"global {a}0; {a}0 = 123")

test('f')

print(f0)

output: 123

https://www.w3schools.com/python/python_variables_global.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM