8

I'm using Python 3.

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

I needed eval for an algebra calculator.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gavin
  • 143
  • 2
  • 2
  • 10

3 Answers3

10

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

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
7

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.

millimoose
  • 39,073
  • 9
  • 82
  • 134
-4

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: ")).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • 2
    But that won't address the OP's use case, which is "an algebra calculator". – DSM Feb 09 '14 at 15:55
  • 2
    You don't seem to understand, input() is only for strings, or I could add int() or float(), but I need to input expressions like (3 * x - 3), which seem to work only with eval. – Gavin Feb 10 '14 at 16:48