Skip to content
Advertisement

globas and exec in python

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

JavaScript

but I am getting result as None

JavaScript

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

JavaScript

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:

JavaScript

Outputs:

JavaScript

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

JavaScript

Outputs:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement