Currently if I test by printing 'ans', it just prints it as a character like ' ' which doesn't work with the equation for 'ans', how do I change this so it adds? what 'ans' prints as
I'm very new to coding so this may seem like an obvious question- sorry!
CodePudding user response:
the right answer for your case is probably to use branching if else
ans = (5,' ',6)
if ans[1] == ' ':
print(ans[0] ans[2])
elif ans[1] == "/":
print(ans[0] / ans[2])
# etc.
you could possibly get away with ast.literal_eval
import ast
ans = (6,'-',2)
eqn = f"{ans[0]} {ans[1]} {ans[2]}"
print("EQN:",eqn,"=",ast.literal_eval(eqn))
the most correct answer however is probably to use a dictionary mapping to deliberately expose specific programmer defined operators
import operator
# the function to call for a given operator
operators = {" ":operator.add,
'-':operator.sub}
ans = (6,'-',2)
operators[ans[1]](ans[0],ans[2])
CodePudding user response:
Change definition of ans to :
ans = eval(str(n1) ops str(n2))
This makes a string of operands and operator stitched together. And then calls eval() function in python which evaluates arithmetic operations denoted by string.
CodePudding user response:
You can do it like this :
def sum(num1,num2):
print(int(num1) int(num2))
operations = {" ":sum}
operator = input("Enter :").split()
operations.get(operator[1])(operator[0],operator[2])
There are many ways to do it or to solve your problem.