0
def calculator():
print("When prompted to enter a symbol, enter:\n'+' to add,\n'-' to subtract,\n'*' to multiply,\n'/' to divide,\n'^' to calculate powers,")
print("',\n'=' to get the answer.")
again = None
while again != "x":
answer = float(input("\nEnter number: "))
while 1 == 1:
symbol = input("Enter symbol: ")
if symbol == "=":
print("\nThe answer is ", answer, ".", sep = "")
again = input("\nEnter 'a' to use the calculator again and 'x' to exit: ")
break
number = float(input("Enter number: "))
#trying to use a dictionary instead of "if" statements present in docstring
dictionary = {"+": answer += number, "-": answer -= number, "*": answer *= number, "/": answer /= number, "^": answer **= number}
dictionary[symbol]
"""if symbol == "+":
answer += number
if symbol == "-":
answer -= number
if symbol == "*":
answer *= number
if symbol == "/":
answer /= number
if symbol == "^":
answer **= number"""
我覺得有一堆「if」語句是WET代碼(如文檔字符串中所示)。我想對基於用戶輸入符號的數字進行操作,但即使我只在字典中保留作爲操作符的符號的值(即,僅「+」:+,「 - 」 : - 等字典)Python:如何使用字典來操作用戶輸入?
編輯: 我想要更少的代碼,所以請不要告訴我做一個函數來調用。
查看['operator'模塊](https://docs.python.org/3/library/operator.html),它提供了常見的操作符作爲函數。 – Evert
@Evert thx工作:) –