0
b = float(input('enter b: ') # where I entered math.exp(2) for b
c = b+4
Gabio
  • 9,126
  • 3
  • 12
  • 32

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.

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 TypeErrors.

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