欢迎访问宙启技术站
智能推送

用Python编写一个简单的计算器

发布时间:2023-12-04 08:48:27

下面是一个简单的基础计算器的Python程序。用户可以输入两个数和运算符,程序将输出计算结果。

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b != 0:
        return a / b
    else:
        return "Error: Division by zero"

def calculator():
    while True:
        num1 = float(input("Enter first number: "))
        operator = input("Enter operator (+, -, *, /): ")
        num2 = float(input("Enter second number: "))

        if operator == "+":
            result = add(num1, num2)
        elif operator == "-":
            result = subtract(num1, num2)
        elif operator == "*":
            result = multiply(num1, num2)
        elif operator == "/":
            result = divide(num1, num2)
        else:
            result = "Error: Invalid operator"

        print("Result:", result)

        choice = input("Do you want to perform another calculation? (Y/N): ")
        if choice.upper() != "Y":
            break

calculator()

使用例子:

Enter first number: 10
Enter operator (+, -, *, /): +
Enter second number: 5
Result: 15.0
Do you want to perform another calculation? (Y/N): Y
Enter first number: 20
Enter operator (+, -, *, /): -
Enter second number: 8
Result: 12.0
Do you want to perform another calculation? (Y/N): Y
Enter first number: 7
Enter operator (+, -, *, /): *
Enter second number: 4
Result: 28.0
Do you want to perform another calculation? (Y/N): Y
Enter first number: 15
Enter operator (+, -, *, /): /
Enter second number: 0
Result: Error: Division by zero
Do you want to perform another calculation? (Y/N): N