使用Python编写一个四则运算程序,要求加,减,乘,除各定义一个函数来实现
时间: 2023-05-11 11:03:45 浏览: 271
好的,以下是一个简单的四则运算程序的 Python 代码:
```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:
raise ValueError("Cannot divide by zero!")
return a / b
operator = input("Enter an operator (+, -, *, /): ")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if operator == "+":
print(num1, "+", num2, "=", add(num1, num2))
elif operator == "-":
print(num1, "-", num2, "=", subtract(num1, num2))
elif operator == "*":
print(num1, "*", num2, "=", multiply(num1, num2))
elif operator == "/":
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid operator!")
```
你可以在命令行中运行这个程序,输入两个数字和一个运算符,程序会输出计算结果。
阅读全文