生成一段Python代码,实现一个简单的计算器功能,可以输入两个数字和一个运算符,输出运算结果。你可以这样输入:

# GPT, please write a Python code that can perform basic arithmetic operations on two numbers.

# GPT's response:

def calculator(num1, num2, operator):
    # check if the inputs are valid numbers and operators
    try:
        num1 = float(num1)
        num2 = float(num2)
        assert operator in ['+', '-', '*', '/']
    except:
        print('Invalid input')
        return
    
    # perform the calculation based on the operator
    if operator == '+':
        result = num1 + num2
    elif operator == '-':
        result = num1 - num2
    elif operator == '*':
        result = num1 * num2
    elif operator == '/':
        # check if the divisor is zero
        if num2 == 0:
            print('Cannot divide by zero')
            return
        else:
            result = num1 / num2
    
    # print the result
    print(f'{num1} {operator} {num2} = {result}')

# test the code
calculator(3, 5, '+')
calculator(10, 2, '/')
calculator(6, 0, '/')
calculator('a', 'b', '*')


更多文章请关注《万象专栏》