'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.



Solution 1:[1]

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

Solution 2:[2]

I think you misplaced the print in your for loop, you should execute the printing of your variable, only executing the variable won't return nor print anything. This should work:

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})")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JuanR
Solution 2 Guilherme Correa