+ 1

Help with input equations in Python

How can I solve an equation in Python if it is inserted as a str Input. For example, input —> (4 * 20) I want to obtain the number 80 but as the input is a string I can not calculate it directly.

2nd Nov 2020, 4:48 PM
Ole Olatz
Ole Olatz - avatar
3 Answers
+ 6
s=input() print(eval(s))
2nd Nov 2020, 4:52 PM
Olivia
Olivia - avatar
+ 1
Using eval for that case is not secure, see the documentation for eval. It is possible to inject "bad" commands. I think the right ways is to use a parser (there are lots of packages available and you do not reinvent the wheel). Over simplified you can use the following code to calculate simple additions and multiplications of integers like 1+2*3: from math import prod s=input() print(sum(map(lambda m: prod(map(int, m.split("*"))), s.split("+")))) With a parser you have to specify a grammer which determin the expresion which could be parsed and considered as valid. I hope that helps.
2nd Nov 2020, 9:45 PM
Manuel Maier
Manuel Maier - avatar
0
str=input() b="print("+str+")" exec(b) https://code.sololearn.com/cYdRBd0061I8/?ref=app
2nd Nov 2020, 10:08 PM
Mohsen Abbaspour
Mohsen Abbaspour - avatar