-3

Here's what I have so far. What I'm trying to do is ask the user for an expression, they input something like 1 + 1 and it's split into x, y, and z. Such that x would be 1, y would be + and z would be the second 1. I'm sure there may be several issues but the main one I'm having right now is converting their input into an int.

x, y, z = input("Expression: ").split()

if y == "+":
    output = x + z
    print(output)

elif y == "-":
    output = x - z
    print(output)

elif y == "*":
    output = x * z
    print(output)

elif y == "/":
    output = x / z
    print(output)
pppery
  • 3,731
  • 22
  • 33
  • 46
majk
  • 1
  • 2
  • There were some inappropriate duplicate links here: despite that there is a list of values, OP wants to convert specific ones, not the entire list (after all, the input is expected to contain things like `/` that are not convertible). That said: it **does not matter** where data comes from in order to solve a problem with the already existing data; it matters what the data **is**. – Karl Knechtel May 18 '23 at 19:03

2 Answers2

-1

You can try for this:

x, y, z = input("Expression: ").split()

x = int(x)
z = int(z)

if y == "+":
    output = x + z
    print (output)

elif y == "-":
    output = x - z
    print(output)

elif y == "*":
    output = x * z
    print(output)

elif y == "/":
    output = x / z
    print(output)
Tanish Gupta
  • 400
  • 2
  • 8
  • 20
-1

The simplest way to do this would be the way that you were doing. But the catch is you have to have spaces between the numbers and the operators like this. 1 + 1

x, y, z = input("Expression: ").split()

output = 0
x = int(x)
z = int(z)
if y == "+":
    output = x + z
elif y == "-":
    output = x - z
elif y == "*":
    output = x * z
elif y == "/":
    output = x / z
print(output)

But if the input is like the following 1+1 where it contains no spaces, then you might get errors. In order to fix that issue the following simple approach can be taken.

import operator
value = input("Expression: ")
ops = {'+':operator.add, '-':operator.sub, '*':operator.mul , '/':operator.truediv}
for i in ops:
    if i in value:
        x,y = value.split(i)
        x = int(x)
        y = int(y)
        print(ops[i](x,y))
        

If your python version is 2, you might want to use operators.div instead of operators.truediv.

Nipuna Upeksha
  • 348
  • 3
  • 15