[英]How can I make this python code look cleaner?
我試圖練習我一直在學習的東西,所以我有了這個想法,它涵蓋了我所學的大部分內容。 該代碼運行良好,但我希望是否有人可以查看並讓我知道如何使它變得更好。
print("available operations (*, +, /, -)\n\"delete\" to delete every previous calculations\n \"exit\" to stop the program ")
is_running = True
op = ""
while is_running:
try:
num1 = float(input(">> "))
except ValueError:
print("ValueError")
continue
while is_running:
op = input(">> ")
if op == "exit":
is_running = False
break
elif op == "delete":
break
try:
num2 = float(input(">> "))
except ValueError:
print("ValueError")
continue
if op == "*":
num1 = num1 * num2
print(num1)
elif op == "+":
num1 = num1 + num2
print(num1)
elif op == "-":
num1 = num1 - num2
print(num1)
elif op == "/":
num1 = num1 / num2
print(num1)
else:
print("unavailable operator")
break
您可以做的一件事是用字典查找替換運算符的條件,如下面的代碼中所述:
import operator
def calculate(op, num1, num2):
oper = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}
try:
return oper[op](num1, num2)
except KeyError:
return 'Invalid Operator'
num1 = 40
num2 = 50
op = '*'
print(calculate(op, num1, num2))
另一件事是您不需要使用多個 try-except 語句。 所有輸入只需一個語句就足夠了。 在第二個輸入語句中也不需要 while 循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.