如何在Python中编写一个计算器函数?
发布时间:2023-09-10 09:00:58
编写一个计算器函数可以通过定义一个函数来实现。在Python中,数学运算可以使用内置的数学模块math来完成。下面是一个简单的例子,展示如何编写一个基本的计算器函数,支持基本的算术运算。
import math
def calculator():
operation = input("请选择要执行的操作 (+, -, *, /): ")
num1 = float(input("请输入 个数字: "))
num2 = float(input("请输入第二个数字: "))
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
else:
print("无效的操作")
return
print("结果: ", result)
# 示例调用
calculator()
以上代码定义了一个名为calculator的函数。该函数首先要求用户选择要执行的操作,然后要求用户输入两个数字。接下来,根据用户选择的操作,进行相应的计算,并将结果打印出来。
这个计算器函数只支持最基本的四则运算,可以根据需要扩展以支持其他更复杂的数学运算。例如,可以使用math模块中的函数来执行三角函数、指数、对数等特殊的数学运算。
import math
def calculator():
operation = input("请选择要执行的操作 (+, -, *, /, sin, cos, sqrt): ")
num = float(input("请输入数字: "))
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
elif operation == "sin":
result = math.sin(num)
elif operation == "cos":
result = math.cos(num)
elif operation == "sqrt":
result = math.sqrt(num)
else:
print("无效的操作")
return
print("结果: ", result)
# 示例调用
calculator()
以上代码通过在用户选择的操作中添加了"sin", "cos", "sqrt"等新的选项,扩展了计算器函数的功能。
