在Python中,实现四则运算可以通过多种方式,包括使用内置的算术运算符、自定义函数或者第三方库。下面是一些示例代码,展示了如何实现四则运算:
使用内置的算术运算符
加法print(1 + 2)减法print(9 - 7)乘法print(23 * 45)除法print(7 / 8)乘幂print(2 3)取整除print(89 // 5)
自定义函数实现四则运算
def add(x, y):return x + ydef subtract(x, y):return x - ydef multiply(x, y):return x * ydef divide(x, y):if y == 0:return "除数不能为0"return x / y使用自定义函数print(add(1, 2))print(subtract(9, 7))print(multiply(23, 45))print(divide(7, 8))
使用第三方库实现四则运算
from fractions import Fractiondef calculator(expression):try:result = eval(expression)return resultexcept Exception as e:return str(e)使用第三方库print(calculator("1 + 2 * 3"))
使用正则表达式解析表达式
import redef evaluate_expression(expression):tokens = re.findall(r'\d+|\+|\-|\*|\/|\(|\)', expression)stack = []for token in tokens:if token.isdigit():stack.append(int(token))elif token in "+-*/":b = stack.pop()a = stack.pop()if token == "+":stack.append(a + b)elif token == "-":stack.append(a - b)elif token == "*":stack.append(a * b)elif token == "/":stack.append(a / b)return stack使用正则表达式解析表达式print(evaluate_expression("1 + 2 * 3 - 4 / 2"))
使用递归实现带括号的四则运算
def evaluate(expression):if '(' not in expression:return eval(expression)open_parenthesis_index = expression.index('(')close_parenthesis_index = expression.index(')')inner_expression = expression[open_parenthesis_index + 1:close_parenthesis_index]result = evaluate(inner_expression)rest_of_expression = expression[:open_parenthesis_index] + str(result) + expression[close_parenthesis_index + 1:]return evaluate(rest_of_expression)使用递归实现带括号的四则运算print(evaluate("1 + (2 * 3) - 4 / 2"))
以上示例展示了Python中实现四则运算的不同方法。你可以根据自己的需求选择合适的方法。需要注意的是,使用`eval`函数时要格外小心,因为它会执行传入的字符串作为代码,可能存在安全风险。如果需要处理复杂的表达式,建议使用第三方库或者自定义解析器来确保安全性。

