0

I am making a calculation program where randomly chosen operator does addition and subtraction of two numbers the problem is that beside showing '+' or '-' sign, the outcome is 9<built-in function add>7 I am writing the code like this

input(num1 + str(operator) + num2, "= ")

1 Answers1

0

Use the eval function to get your answer: Python eval function

Basically it just evaluates a string for mathematical, etc. operations and functions.

answer=eval(str(num1)+"[operator]"+str(num2))

So if num1 was 9 and num2 was 7 and your operator was "-", you would end up with:

answer=eval("9-7")

and it would do the operation and return 2

user2525692
  • 31
  • 1
  • 6
  • the operator is randomly chosen so I don't think this is right – Kutttayqarateraa Mar 22 '15 at 02:40
  • Yes, get your random operator by doing `random.choice(["+","-","*","/"])` then put that value into where [operator] is. – user2525692 Mar 22 '15 at 02:43
  • I had tried that before but apparently it doesn't work – Kutttayqarateraa Mar 22 '15 at 02:48
  • Are you getting an error or does it just not work? If so, please tell me what error you are getting – user2525692 Mar 22 '15 at 02:49
  • ` op = random.choice("+", "-") #this variable randomly selects the operator TypeError: choice() takes 2 positional arguments but 3 were given` – Kutttayqarateraa Mar 22 '15 at 02:56
  • Don't forget to use brackets [] since you are selecting an option from an array: `op = random.choice(["+", "-"])` – user2525692 Mar 22 '15 at 03:09
  • I missed it before but still getting the same error by using it @user2525692 – Kutttayqarateraa Mar 22 '15 at 03:23
  • 1
    What version of python are you using and what is your _exact_ line of code? Once you import random, you should be able to use the code I posted earlier. @Kutttayqarateraa – user2525692 Mar 22 '15 at 03:39
  • 1
    It's not a good idea to use `eval()` unless you know _exactly_ what you're doing. It is actually safe to use `eval()` here, but it can be very [dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) on arbitrary strings. So it's not a good habit to get into using `eval()`, it's _much_ better to solve problems in a way that doesn't need it. – PM 2Ring Mar 22 '15 at 04:09