![](/img/trans.png)
[英]Python: How can I assign string representations of operators to mathematical operators using a dictionary?
[英]How to store and use mathematical operators as python variable
我是python的新手,並且正在嘗試編寫類似下面的內容(代碼A),因此它與代碼B完全一樣。我想利用數學運算符的用戶輸入作為do_what
變量。 我們如何在python中編寫這段代碼(A),這樣它就像代碼B一樣工作?
代碼A.
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter a calculation symbol for calculation you want to perform: ")
result = float(num1) do_what float(num2)
print("result is: " + str(result))
代碼B.
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = int(num1) + int(num2)
print("result is: " + str(result))
您可以將操作員模塊用於公共運算符,並創建查找字典以將符號映射到函數。 如果您希望運算符不在該模塊中,您只需定義自定義函數並添加以相同的方式查找它們:
import operator
operatorlookup = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter calculation symbols for calculation you want to perform: ")
op = operatorlookup.get(do_what)
if op is not None:
result = op(float(num1), float(num2))
else:
result = "Unknown operator"
print("result is: " + str(result))
您可能也有興趣了解內置函數eval 。 這會將if
和else
循環減少為您的特定示例的單個語句
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter calculation symbols for calculation you want to perform: ")
result = eval(num1 + do_what + num2)
print("result is: %s" %result)
# Enter a number: 3
# Enter another number: 18
# Enter calculation symbols for calculation you want to perform: *
# result is: 54
編輯
為了在這種特殊情況下使eval
略微安全,你可以使用這樣的東西
if do_what in ['+', '-', '*', '**', '/']:
result = eval(num1 + do_what + num2)
print("result is: %s" %result)
else:
print ("Enter an arithmetic operator")
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
do_what = input("Enter calculation symbols for calculation you want to perform: ")
if do_what=='+':
result = float(num1) + float(num2)
elif do_what=='-':
result = float(num1) - float(num2)
elif do_what=='*':
result = float(num1) * float(num2)
elif do_what=='/':
result = float(num1) / float(num2)
print("result is: " + str(result))
如果您不關心安全性,可以使用eval來實現此目的
result = eval(str(num1) + do_what + str(num2))
問題是,eval會逐字地評估你編寫為python代碼的所有內容,所以不要這樣做,如果你的意思是讓其他人使用它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.