Skip to content

eval input in Python

  • by

You can feed input into eval() and evaluate it as a Python expression. The built-in input() reads the user input at the command line, converts it to a string, strips the trailing newline, and returns the result to the caller.

x = eval(input("Enter a number: "))

You can wrap Python’s eval() around input() to automatically evaluate the user’s input.

eval(input()) in Python

Simple example code Using Python’s eval() With input().

x = eval(input("Enter a math expression: "))
print(x)

Output:

eval input in Python

Note: x = eval(input("Enter a number: ")) is not the same thing as x = eval('input("Enter a number: ")')

Difference between eval(“input()”) and eval(input()) in Python

Answer: eval evaluates a piece of code. input gets a string from user input. Therefore:

  • eval(input()) evaluates whatever the user enters. If the user enters 123, the result will be a number, if they enter "foo" it will be a string, if they enter ?wrfs, it will raise an error.
  • eval("input()") evaluates the string "input()", which causes Python to execute the input function. This asks the user for a string (and nothing else), which is while 123 will be the string "123", ?wrfs will be the string "?wrfs", and "foo" will be the string '"foo"' (!).

A third version that might make the difference apparent: eval(eval("input()")) is exactly identical to eval(input()).

Source: https://stackoverflow.com/questions

Do comment if you have any doubts or suggestions on this Python eval topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *