Home > Mobile >  globas and exec in python
globas and exec in python

Time:04-23

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.

CodePudding user response:

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

CodePudding user response:

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