Can I use a variable in place of a math operator?

277 Views Asked by At

What I'm trying to do is ask the user for a type of math operator(Not sure if I used the correct term. I'm new to python.), and use that in place of a math operator in an equation.

Here I tried:

math_thing = int(input('Enter a type of math operator(/,*,+,etc.,)'))
result = 12{0}4.format(math_thing)
print(result)

I was expecting it to ask for a sign, and perform the equation(I was going to add checks to see if it was valid), but what happened was it gave me the error SyntaxError: invalid syntax. I don't really know any other way to do it, and when I looked I thought the .format thing might only work for strings, but I'm not sure.

2

There are 2 best solutions below

1
catasaurus On

It is not a generally good idea to use eval in python, because the user of the program could input malicious code. So make sure only trusted users are using this program on your computer. Also I got rid of int on the input function as it is not needed:

math_thing = input('Enter a type of math operator(/,*,+,etc.,)')
result = eval('12{0}4'.format(math_thing))
print(result)

Output (when input is *):

48

All that eval does is take a string (a str object) of python code and run it.

Please do keep in mind though that you should never use a program of this type using eval on any system that you are exposing to the internet, because that would make it so anybody any where could run python code on your computer, potentially malicious code.

1
Nibrock On

If you're attempting to make a program to perform an equation between two numbers, one solution is to do it in an if statement.

For Example:
operator = input('Enter a type of math operator(/,*,+,etc.,)')
if operator == '*'
    result = firstnumber * secondnumber
if operator == '/'
    result = firstnumber * secondnumber
...and so on
print(result)