Skip to content
Advertisement

globas and exec in python

I have written code, to create variable and assign values using for loop.

nums = [0,1,2,3]
names = ["aa","bb","cc","dd"]

for num, name in zip(nums, names):
    globals()["df"+str(num)]= names[num]
    print(exec(f'df{num}'))

but I am getting result as None

#result:

None
None
None
None

but even I tried to change the code with below modification, still getting the same

nums = [0,1,2,3]
names = ["aa","bb","cc","dd"]

for num, name in zip(nums, names):
    globals()["df"+str(num)]= name
    print(exec(f'df{num}'))

Can some one help me to get the proper answer for this.

Note: even I used exec function in the place of name (ex: exec(f'{names[num]}’) then I am getting name error.

Advertisement

Answer

Considering that exec returns None, I don’t see why you would expect otherwise.

Try changing a little bit your code to see it is working correctly, for example:

nums = [0,1,2,3]
names = ["aa","bb","cc","dd"]

for num, name in zip(nums, names):
    globals()["df"+str(num)]= name
    exec(f'print(df{num})')

Outputs:

aa
bb
cc
dd

Update: If you want to return something, you must use eval:

nums = [0,1,2,3]
names = ["aa","bb","cc","dd"]

for num, name in zip(nums, names):
    globals()["df"+str(num)]= name
    print(eval(f'df{num}'))

Outputs:

aa
bb
cc
dd
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement