Quick actions

cmd+k|ctrl+k

Navigation

Languages

20250805_erb_python_lesson10_6

Snippet info

Language

Python

Visibility

public

Author

phyllisyau

Created

2025-09-05T13:49:56.102564Z

Updated

2025-09-05T13:50:07.170059Z

def check_operand(operand):
    try:
        return float(operand)
        except ValueError:
            print("wrong Input value")
            return None
def check_operator(operator):
    if operator in ["+", "+", "-", "*", "/"]:
        return True
def check_odd(length):
    if length % 2 and length >=3:
        return True
    else:
        return False
expression = input("Please input expression with spacing for calculation : ")
expression = expression.split()
# check a valid expression before jump into while loop
if check_odd(len(expression)):
    # valid length of expression
    while(check_odd(len(expression))):
        x = expression[0]
        op = expression[1]
        y = expression[2]
        # check first operand or exit the while loop without further calculation
        if check_operand(x):
            x = check_operand(x)
        else:
            break
        #check second operand or exit the while loop
        if check_operand(y):
            y = check_operand(y)
        else:
            break
        # final check of operator then perform calculation
        if check_operator(op):
            if op == '+':
                result = x + y
            if op == '-':
                result = x - y
            if op == '*'
                result = x * y
            if op == '/':
                if y == 0:
                    print("value overflow !")
                    break
                else:
                    result = x / y
        else:
            print("invalid operator !")
            break
        del expression[:2]
        expression[0] = result
    else: # if expression is short then print the final result
        print(f"The expression result is : {result})
    else:
        print("invalid expression, can't calculate !")
INFO