0

I'm trying to write a program that asks a user to input an expression (ex: '2 + 2') and assign variables to each string ('x = 2', 'y = +', 'z = 2') and have it output a float with sig figs at the tenths place ('4.0').

My thought process was to change the variable str values to int, output the answer to the expression based on whatever operator is assigned for y ('+', '-', '*', or '/'), and then change this to a float with the proper number of decimals.

The issue is, any code I try to write with the "y" assigned variable (the assigned operator) gives me an indicator of invalid syntax. By doing 'x + y + z' I'm told TypeError: unsupported operand type(s) for +: 'int' and 'str'. I'm not sure why if y is being assigned as an operator. I'm guessing the '+' value it's being read as a str, but I don't know what to assign it as to convert it to be useable in an equation.

# Prompt user input
expression = input("Expression: ")

#Assign str to a list of variables at once
x, y, z = expression.split(" ")

# Convert string to integer, string to operator

# Convert X to int
x = int(x)
# Convert Y to...?
y = '-' or '+' or '*' '/'
# Convert Z to int
z = int(z)

# Convert expression to float
answer = float(x + y + z)

# Format answer to output to the tenths place
format_answer = "{:.1f}".format(answer)
print(format_answer)
martineau
  • 112,593
  • 23
  • 157
  • 280
  • your "y" variable holds an operand, but the expression `float(x + y + z)` is assuming addition and then trying to add two numbers and an operand, eg. if you input "2 / 2" your code is trying to do `float(2 + '/' + 2)` – Kurt Apr 18 '22 at 23:31

0 Answers0