python计算器简单代码

当创建一个简单的 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: Cannot divide by zero."

while True:
# 获取用户输入
num1 = float(input("请输入第一个数字: "))
operator = input("请输入运算符 (+, -, *, /): ")
num2 = float(input("请输入第二个数字: "))

# 执行计算
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:
print("无效的运算符")
continue

# 显示结果
print("结果: ", result)

# 询问用户是否

如果你想扩展这个简单计算器的功能,可以考虑添加其他数学运算或改进用户界面。例如,你可以添加取余数、幂运算等功能,或者使用图形用户界面库来创建更友好的计算器界面。

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: 不能除以零."

def modulus(x, y):
if y != 0:
return x % y
else:
return "Error: 不能对零取余."

def power(x, y):
return x ** y

while True:
num1 = float(input("请输入第一个数字: "))
operator = input("请输入运算符 (+, -, *, /, %, **): ")
num2 = float(input("请输入第二个数字: "))

if operator == "+":
result = add(num1, num2)
elif operator == "-":
result = subtract(num1, num2)
elif operator == "*":
result = multiply(num1, num2)
elif operator == "/":
result = divide(num1, num2)
elif operator == "%":
result = modulus(num1, num2)
elif operator == "**":
result = power(num1, num2)
else:
print("无效的运算符")
continue

print("结果: ", result)

again = input("要

标签