1

I'm writing a program that, among other things, takes in user input for the entries of a matrix. These entries currently can be integers or floats - like

value_list.append(float(input("what value for position _, _: ")))
#value_list is then resized into a numpy matrix

(There's more to it than this, but this is basically what I'm doing.)

It would be much more useful for the user to be able to input square roots, imaginary numbers, and constants like pi or e. Looking around on the internet, I quickly found the eval() function, but this seems like a poor solution. What other options do I have?

Auden Young
  • 1,147
  • 2
  • 18
  • 39
  • 1
    You can parse the input for 'i' for imaginary, or 'sqr' for a square root or something similar? – Reedinationer Mar 15 '19 at 20:47
  • 2
    Your correct heather. `eval` isn't a good solution. It's dangerous and and overpowered for your needs. However, the concept behind using `eval` - parsing - is a good solution. Look into methods for parsing strings. A library such as [Pyparsing](https://github.com/pyparsing/pyparsing) comes to mind. See [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) for an example usage of Pyparsing. Or, if you prefer, you could hand write a simple parser. – Christian Dean Mar 15 '19 at 20:48
  • @Reedinationer I could; I wasn't sure what built-in/already written options were out there. – Auden Young Mar 15 '19 at 20:49
  • Well I think the link Christian gave you is probably close to what you are looking for then! – Reedinationer Mar 15 '19 at 20:51

0 Answers0