# 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.

  • rtxn@lemmy.world
    link
    fedilink
    arrow-up
    18
    arrow-down
    1
    ·
    edit-2
    10 hours ago

    Change this:

        print(calculate(splitter(expression)))
    

    to this:

        print(calculate(* splitter(expression)))
    

    The error is that calculate expects three float values (x, and y, and z), but splitter returns a tuple object ((x, y, z) as one object, similar to arrays in other languages):

    >>> type(splitter("1 + 2"))
    <class 'tuple'>
    

    Prepending a tuple or a list with a * operator (unpacking or splatting) unpacks the object into its individual items that are then passed to the function as separate arguments.

    In fact, str.split() already returns a tuple. By assigning multiple values at once in x, y, z = expression.split(), you actually unpack the returned tuple into individual values, then in return x, y, z, you pack those values into a tuple.