在 python 中将运算符分配给变量?
- 2025-03-12 08:55:00
- admin 原创
- 19
问题描述:
将数学应用于变量的常用方法是
a * b
它能像这样计算并操作两个操作数吗?
a = input('enter a value')
b = input('enter a value')
op = raw_input('enter a operand')
那么我该如何连接 op 和两个变量a
and b
?
我知道我可以将 op 与+
、-
、进行比较%
,$
然后分配和计算....
但是我可以做一些事情,例如a op b
,如何告诉编译器 op 是一个运算符?
解决方案 1:
您可以使用操作符模块和字典:
import operator
ops = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.div
}
op_char = input('enter a operand')
op_func = ops[op_char]
result = op_func(a, b)
解决方案 2:
运算符模块http://docs.python.org/library/operator.html公开了与几乎所有 Python 运算符相对应的函数。您可以将运算符符号映射到这些函数以检索适当的函数,然后将其分配给您的 op 变量并计算 op(a, b)。
解决方案 3:
我知道这是一个非常古老的话题,但我相信当时人们并不知道这个eval
函数(也许它是 Python 3 附带的)。所以这是对这个问题的更新答案
a = input('enter a value')
b = input('enter a value')
op = input('enter an operand')
expression = a + op + b # simple string concatenation
result = eval(expression)
如果输入不期望始终有效,ast.literal_eval
则可以改用。如果输入不是有效的 Python 数据类型,则会引发异常,因此如果不是,则不会执行代码。例如,如果a
、b
和op
分别为 5、10、+,result
则为 15
解决方案 4:
您可以使用 operator 模块来创建字典。从该模块的Python 3 文档中:
“operator 模块导出一组与 Python 固有运算符相对应的高效函数。例如,operator.add(x, y) 相当于表达式 x+y。”
import operator
ops = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv
}
op_char = input('enter a operand')
a = 1
b = 2
result = ops[op_char](a,b)
print(result)
解决方案 5:
您需要手动将用户输入的字符串与您的操作数列表进行比较。这里没有 int() 的类似物,因为运算符是语言中的关键字而不是值。
将输入字符串与操作数列表进行比较并确定其对应的运算符后,可以使用 Python 标准库的运算符模块来计算将运算符应用于两个操作数的结果。
解决方案 6:
a = int(input("Give a number for an operation: "))
b = int(input("Give a number for the other operation: "))
operation = input("Choose a math operation (+, -, *, /): ")
if operation == "+":
result = a + b
elif operation == "-":
result = a - b
elif operation == "*":
result = a * b
elif operation == "/":
result = a / b
else:
result = "Invalid operation"
print(f"The result is: {result}")
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD