-1

I am trying to run this in Python IDLE:

>>> eval(print("123*13"))

I get the output correctly, but it comes with a TypeError:

123*13
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    eval(print("123*13"))
TypeError: eval() arg 1 must be a string, bytes or code object

NOTE:
I do NOT want to do print(eval("123*13")).
I want to use print() in eval() function. This is NOT for actual implementation, but I got this error while using eval() function. I am not asking this for any actual implementation, but curiosity.

CoolCoder
  • 786
  • 7
  • 20

1 Answers1

3

Use it:

eval('print("123*13")')

in eval() src:

evel (__source: str | bytes | CodeType, __globals: Dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ...) -> Any
'''Evaluate the given source in the context of globals and locals.

The source may be a string representing a Python expression    
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.'''
...

eval help():

eval(source, globals=None, locals=None, /)
    Evaluate the given source in the context of globals and locals.

    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

You can see more in Python.org.

  • 2
    Thank you @Delta for the answer. It seems that `eval()` function needs only `str` as input, so the `print()` function too must be as a `str`. – CoolCoder May 14 '21 at 15:06
  • str formats: `'''str''', """str""", 'str', "str", '\'str\'', ... –  May 14 '21 at 16:29