# Ask user to enter an expression and display output
def main():
    expression = input("Expression: ")

    print(calculate(splitter(expression)))


# Split expression into components and assign to variables as float values
def splitter(expression):
    x, y, z = expression.split()

    return x, y, z

# Calculate expression result
def calculate(x, y, z):
    x, z = float(x), float(z)

    if y == "+":
        return str(round((x + z), 1))
    elif y == "-":
        return str(round((x - z), 1))
    elif y == "*":
        return str(round((x * z), 1))
    else:
        return str(round((x / z), 1))



main()

I am getting traceback errors for any expression (1 + 1) I enter.

  • cherrykraken@lemmy.ca
    link
    fedilink
    arrow-up
    6
    arrow-down
    1
    ·
    edit-2
    5 hours ago

    Functions in Python can only return a single value. While you are allowed to comma-separate additional values, as you have done, they are combined into a single tuple object that wraps the intended values.

    As such, your splitter function is returning a single tuple containing three strings. Your calculate function is expecting three individual arguments (I’m guessing that the error trace mentions this).

    To get around this, you can use the splat/asterisk operator to “unpack” the items from the tuple:

    a, b, c = splitter(expression)
    # or, inline
    calculate(*splitter(expression))
    

    Edit: removed bad asterisk

    • Eager Eagle@lemmy.world
      link
      fedilink
      English
      arrow-up
      7
      ·
      edit-2
      6 hours ago

      Functions in Python can only return a single value

      that’s not true accurate, this is valid code in this context:

      x, y, z = splitter(expression)
      

      Where x, y, and z are strings. But when you do this, akin to what OP did:

      value  = splitter(expression)
      

      then value is a tuple of 3 strings.

      In fact, unpacking with asterisk at assignment, like below, is not allowed:

      x, y, z = *splitter(expression)
      
          x, y, z = *splitter(expression)
                    ^^^^^^^^^^^^^^^^^^^^^
      SyntaxError: can't use starred expression here