0

I am looking to make a program where the user enters a sum eg. 5 + 6 - 7, and my program recognise's it and gives the answer eg 4. So far my program will take the input, recoginises the numbers and operations, and assigns them to a list, however, I am not sure how to take the numbers and operators and calculate them. Does anyone have anything that could help??

Here is my code

s = "5 + 6 - 7" #User input placeholder

q = s.split() #splits the input into a list with an element for every character(not spaces)
print(q)

n = [] #numbers in user input
a = [] #actions/operations that the user inputs

print(q)


for x in range(0, len(q)):
    if q[x].isdigit(): #determines whether an element is a digit
        q[x] = int(q[x]) #str to int
        n.append(q[x]) #adds it to the n list
        print(n)
    else:
        a.append(q[x]) #adds an operation to the a list
        print(a)

answer = n[0], a[0], n[1], a[1], n[2]

print("Operations are: ", a)
print("Numbers are: ", n)
print("Answer is: ", answer)
Hugo Phelan
  • 15
  • 1
  • 6
  • This question was already asked: https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string – Omri Levi Jun 12 '20 at 13:59
  • Does this answer your question? [How can I convert string to source code in python?](https://stackoverflow.com/questions/43878504/how-can-i-convert-string-to-source-code-in-python) – Tabish Mir Jun 12 '20 at 14:00
  • Neither of those are useful if your goal is to attempt to implement a simple parser by yourself, instead of just calculating what the user has given you. In that case using a library is the sane way to do it, but it won't let you learn how you could do something fragile, but similar. – MatsLindh Jun 12 '20 at 14:07

2 Answers2

3

The operator module gives you direct access to all the standard operators in Python as functions.

You can assign each operator function to its textual representation and use that to look up the operators:

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

Running through your numbers and operators, you pick two arguments off your list for each operation and apply it, before pushing the result back in the list:

print("Operations are: ", a)
print("Numbers are: ", n)

for operation in a:
    arg_a = n.pop(0)
    arg_b = n.pop(0)

    result = ops[operation](arg_a, arg_b)
    n.insert(0, result)

print("Answer is: ", n[0])

The element that's left in your n list is the answer to the calculation as requested. This assumes that the calculation is well-formed.

MatsLindh
  • 49,529
  • 4
  • 53
  • 84
-1

In such case you can use eval() which recognizes the expression and calculates the output.

for example,

s = "5 + 6 - 7"
print(eval(s))

output:

4

It is the simplest thing you can do.Hope this helps you!

Prathamesh
  • 1,064
  • 1
  • 6
  • 16