0
b = float(input('enter b: ') # where I entered math.exp(2) for b
c = b+4
Gabip
  • 6,159
  • 3
  • 5
  • 19

2 Answers2

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.

jo3rn
  • 1,061
  • 1
  • 7
  • 20
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 TypeErrors.

For floats or other patterns this post might be helpful: Matching numbers with regular expressions — only digits and commas

Musab Guma'a
  • 147
  • 1
  • 9