5 Years
Discussion Span
Last Post by pyTony

I did not guess the right answer.
I did now that that exec "print(a+b)" evaluate to 7 and that dict(a=6, b=9) make a dictionary.
So False was my guess because 7 in not in that dictionary,and only 'a' and 'b' would return True.
I did probably know that this was the wrong guess and that there where a catch.

So i looked into it and my understaning of this is.

>>> a = 2
>>> b = 5
>>> globals()
{'a': 2, 'b': 5, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}}

So when exec "print(a+b)" run it look into globals() and find that a is 2 and b is 5.
Then evaluate that and output 7.

But when we use exec with in,exec dos not look into globals(),
but it look into the given dictionary.
There it find that a is 6 and b is 9 and we get output of 15 wish is the correct answer.
Feel free to correct me if something i sad is wrong.

Edited by snippsat


Your thinking before checking the answer is little misguided, what does this produce in c

>>> from __future__ import print_function
>>> a = 2
>>> b = 5
>>> c = print(a+b)
>>> print(c)

and this would print 5

>>> exec "2+3"

but it does not print nothing and exec is command, not function.

The explanation on what happens is basically correct, only the globals given in dictionary after in exist inside exec, without in, exec uses the globals() dictionary. So this gives error:

 b = 4
 exec "a+b" in dict(a=3)

Usually you would give dictionary variable to save the state after execution:

>>> d = dict()
>>> exec 'a=3.1415*2' in d
>>> print d.keys()
['__builtins__', 'a']
>>> d['a']

Edited by pyTony

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.