Search code examples
python-3.xeval

print(eval("print(2+3)")) prints 2 different answer


I was doing basic python Hackerrank challanges when there was this challange; get the input line as string and pass it to eval and print it. As an example given input was

print(2+3)

When I executed the same code as in title it printed 2 different answers. Those were

5
None

Is this happening because of Hackerrank's compiler or is it a common thing in python?

Edit: I am curious because I thought eval returns only 1 thing.


Solution

  • The second value is what the function evaluates to, i.e. the return value of the function. The return value of the print() function is None. Thus, your eval() call will evaluate print(2+3), which evaluates to None. The 'side-effect' is that the print() function prints some values, which occurs before the function return.