I tested these under python 2.6 and 2.7.
See this is OK:
>>> exec ‘e=1’
>>> exec ‘f=2’
>>> exec ‘g=e+f’
>>> print g
3
But this returns error:
>>> cont=[‘e=1′,’f=2′,’g=e+f’]
>>> for e in cont:
… try:
… exec e
… except Exception,em:
… print em
…
cannot concatenate ‘str’ and ‘int’ objects
So why?
Thanks!
You’ve chosen your variable names poorly. You’re using
eas both theforloop variable and the int variable incont[0]. What happens is that the first time through the loop,e == 'e=1'; thenexec eis called ande == 1; then the next time through the loop,e == 'f=2', and so on. By the time the last expression'g=e+f'isexeced,eis no longer an int, but a string — the string'g=e+f'.