以下是一个简单的计算器程序的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 "Error: division by zero"
    return a / b

print("Welcome to the calculator program!")
print("Please enter two numbers and the operation you want to perform.")

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

operation = input("Enter the operation (+, -, *, /): ")

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

print("The result is:", result)

该程序首先定义了四个函数,分别实现加、减、乘、除四种基本运算。然后,程序会提示用户输入两个数字和要执行的操作。根据用户输入的操作符,程序会调用相应的函数进行计算,并输出结果。如果用户输入了无效的操作符或除数为零,则程序会输出错误信息

用python编程实现一个简单的计算器

原文地址: https://www.cveoy.top/t/topic/fiJr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录