Siddharth Sengupta
Siddharth Sengupta

Reputation: 35

How to run the math from an input in python

I am creating a game in python where I need to run basic math operations. These operations would be provided by a user as input. How do I do this?

So far, I have independent variables for each number and each operator, however, when I run the code, it does not recognize the operator ('+','-','*','/') as an operator, but rather as strings. Therefore, when running the programming it would run as 1'+'1.

print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)

vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)

vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)

vsofar = (vinput1, vop1, vinput2)
print(vsofar)

Computer's output:

(1, '+', 1)

Upvotes: 2

Views: 15478

Answers (5)

Ugochukwu Nnachor
Ugochukwu Nnachor

Reputation: 1

num1= int(input("first number: "))
num2= int(input("2md number: "))
sign= input("sign operator: ")

if sign == '+':
    print("Answer is", num1+num2)
elif sign == '-':
    print("Answer is", num1-num2)
elif sign == '*':`enter code here
    print("Answer is", num1*num2)
elif sign == '/':
    print("Answer is", num1/num2)
else:
    print("am not built to use this sign yet")

Upvotes: 0

Paul Rooney
Paul Rooney

Reputation: 21609

While eval operates in a very general context and so much scope for introducing security issues ast.literal_eval is intended to evaluate string literals only and so has a far narrower and hence safer scope.

from ast import literal_eval

print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)

vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)

vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)

vsofar = (vinput1, vop1, vinput2)

print(literal_eval(''.join(map(str, vsofar))))

Otherwise create a mapping from operators to functions to lookup the function to call for each operator.

import operator
import sys

ops = {'+': operator.add, 
       '-': operator.sub}

v1 = int(input('enter first num'))

op1 = input('input operator')

if not op1 in ops:
    print('unsupported operation')
    sys.exit(1)

v2 = int(input('enter second num'))

print(ops[op1](v1, v2))

The great thing about this is that you don't have to screw around in the program logic to add new (binary) operations. You just add them to the dict, with far less opportunity to make a typo in a long if/elif chain.

Upvotes: 1

BusyProgrammer
BusyProgrammer

Reputation: 2791

The safest and simplest method is to use an if-statement to check which symbol was input. A sample if-statement would be:

print("Now you can solve it. ")
vinput1=int(input("Please input the first number"))
print("First number is recorded as", vinput1)
vop1=input("Please input your first operator")
print("Your operator is recorded as", vop1)
vinput2=int(input("Please input the second number"))
print("Second number is recorded as", vinput2)

if (vop1 == "-"):
    vsofar = vinput1 - vinput2
    print(vsofar)
elif (vop1 == "+"):
    vsofar = vinput1 + vinput2
    print(vsofar)
elif (vop1 == "/"):
    vsofar = vinput1 / vinput2
    print(vsofar)
elif (vop1 == "*"):
    vsofar = vinput1 * vinput2
    print(vsofar)
else
    print("Invalid operator entered.")

Just to quickly explain, these if-statements check whether the operator entered, which is stored in vop1, matches the -, +, *, or / operator. If it matches any of these, then its respective operation is carried out and stored in the variable vsofar,cwhich is printed in the line after that operation. If none of the operations work, then an invalid statement is printed.

This is the most bland, simple, and somewhat long way of doing it. However, the eval() function is not safe to use. A shorter yet more complex than my way is the answer of Paul Rooney.

Hope this helps!

Upvotes: 0

Matthew Plemmons
Matthew Plemmons

Reputation: 112

If you don't want to use eval() you might try a series of conditionals to test the operator and then perform the correct calculation based on that.

if vop1 == "+":
    return vinput1 + vinput2
if vop1 == "-":
    return vinput1 - vinput2

Upvotes: 0

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

You Can evaluate!

>>> input1=1
>>> input2=3
>>> vop1="+"
>>> print eval(str(input1)+vop1+str(input2))
4

Have a look at this

Hope this helps!

Upvotes: 0

Related Questions