Python3, best alternatives to eval()? (input as an expression)

Question:

I’m using Python 3.

How can I input an expression without using eval(input("Input: "))?

I needed eval for an algebra calculator.

Asked By: Gavin

||

Answers:

how can I input an expression without using eval(input("Input: "))

Simply don’t use eval. In Python 3.x, input is the replacement for raw_input, so you don’t need eval. You can simply write your statement as input("Input: ").

Moreover, in Python 2.X, you should have used raw_input("Input: ") instead of eval(input("Input: ")).

Answered By: Abhijit

If you’re the only person using that app and thus don’t need to be worried about security issues, just keep using eval() or exec().

Otherwise, just use a safe library for the specific task you need. E.g. numexpr I guess for a calculator.

Answered By: millimoose

Depending on how complicated your expressions are, ast.literal_eval may be a safer alternative.

Answered By: Hugh Bothwell
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.