b = float(input('enter b: ') # where I entered math.exp(2) for b
c = b+4
Asked
Active
Viewed 60 times
0

Gabio
- 9,126
- 3
- 12
- 32
-
2`float` does not evaluate expressions. You might try `eval`, but should be _very_ careful with that. Also, requires `math` to be imported first. – tobias_k Jul 06 '20 at 14:58
-
https://stackoverflow.com/a/9558001/6260170 – Chris_Rands Jul 06 '20 at 15:04
-
eval worked perfectly. Thanks – Lawrence Ankutse Jul 06 '20 at 15:13
-
I second @tobias_k. Do make sure you check your input value prior to sending along to `eval`. Also, welcome! – Jason R Stevens CFA Jul 06 '20 at 15:36
2 Answers
1
You can use eval:
import math
b = input("enter b: ")
if not 'math.exp(' in b: # add to this list with what you'd like to allow
raise ValueError
b = eval(b) # e.g. math.exp(2) as input
c = b + 4
print(c)
Be aware that without checking inputs users could input expressions that you would not like to be evaluated.

Jason R Stevens CFA
- 2,232
- 1
- 22
- 28

jo3rn
- 1,291
- 1
- 11
- 28
0
Regex may be a good option:
import re
import math
exp_pattern = "math.exp([^\d+$])"
equation = input("Enter an Expression : ")
if re.match(exp_pattern, equation):
b = math.exp(re.compile(exp_pattern).search(equation).group(1))
c = b + 4
print(c)
else:
raise ValueError("Invalid Expression")
The regex pattern will only match integers so no unexpected TypeError
s.
For floats or other patterns this post might be helpful: Matching numbers with regular expressions — only digits and commas

Musab Guma'a
- 175
- 2
- 9