Why do I get None in output in second line while using eval function?

Question:

I am executing this line of code –

print(eval("print(2 +3)"))

but this instead of giving output as 5 gives output-

5
None
Asked By: TusharGaurav

||

Answers:

When you try to get eval of something like
eval("2")
you are actually going to get type int.

But trying to evaluate print expression gives you None type. Print will be executed but type of
eval("print(2+3)")
will be None.

Answered By: Janko Ljubić

This is because you are giving eval() within print().

eval("(2 +3)")

This will return 5 as the function eval returns the value 5 which gets printed using the print()

But,

print(eval("(2 +3)"))

Here inside the eval() you have used print(). So the inner print() prints the value 5 and the function eval() returns None as it has nothing to return. That None gets printed by the outer print()

print() sometimes prints single None or None after value.

For don’t print the None need to use define function.

May be your question was from Hackerrank.

I had a problem today.

And it is my answer.

def ev(expression):
  return eval(expression)
ev(input())
Answered By: Herzeg
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.