python简单数学运算器
时间: 2024-09-29 20:14:45 浏览: 43
大爽Python入门教程1-1简单的数学运算.pdf
Python是一种高级编程语言,非常适合编写简单的数学运算器。你可以通过基本的算术运算符如加 (+), 减 (-), 乘 (*), 除 (/) 和取余 (%), 来创建功能齐全的计算器程序。以下是一个简单的例子:
```python
# 定义一个函数来进行加法运算
def add(x, y):
return x + y
# 定义减法、乘法和除法函数类似
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
return "Error: Division by zero is not allowed."
# 用户输入操作和数字
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
result = divide(num1, num2)
print(num1, "/", num2, "=", result)
else:
print("Invalid input")
阅读全文