Yet Another Newbie Question (YANQ)

Simon Brunning SBrunning at trisystems.co.uk
Wed Feb 21 04:09:51 EST 2001


> From:	David A. [SMTP:man_at_moon at hotmail.com]
> I have this problem:
> 
> >>> a='a'
> >>> prt='print'
> >>> t=prt+' '+a
> >>> t
> 'print a'
> 
> now when I try to:
> >>> eval(t)
> Traceback (innermost last):
>   File "<pyshell#18>", line 1, in ?
>     eval(t)
>   File "<string>", line 1
>     print a
>         ^
> SyntaxError: invalid syntax
> 
> can someone explain me what I am doing wrong! Why can't I use eval(print)?
> Any help is welcome!
 
eval evaluates a Python expression - 'print a' isn't an expression. Use eval
like this:

>>> spam = '1 + 4'
>>> eggs = eval(spam)
>>> print eggs
5

What *you* want is 'exec'. try this:

>>> a = 'a'
>>> prt='print'
>>> t=prt+' '+a
>>> t
'print a'
>>> exec(t)
a

Cheers,
Simon Brunning
TriSystems Ltd.
sbrunning at trisystems.co.uk

On two occasions I have been asked (by members of Parliament!), 'Pray, Mr.
Babbage, if you put into the machine wrong figures, will the right answers
come out?' I am not able rightly to apprehend the kind of confusion of ideas
that could provoke such a question. - Charles Babbage




-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.




More information about the Python-list mailing list