這裏的數學運算是在Python計算器代碼:簡化代碼 - 執行基於運營商
import time
#Returns the sum of num1 and num2
def add(num1, num2):
return num1 + num2
#Returns the difference of num1 and num2
def subtract(num1, num2):
return num1 - num2
#Returns the quotient of num1 and num2
def divide(num1, num2):
return num1/num2
#Returns the product of num1 and num2
def multiply(num1, num2):
return num1 * num2
#Returns the exponentiation of num1 and num2
def power(num1, num2):
return num1 ** num2
import time
def main():
operation = input("What do you want to do? (+, -, *, /, ^): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/" and operation != "^"):
#invalid operation
print("You must enter a valid operation")
time.sleep(3)
else:
var1 = int(input("Enter num1: ")) #variable one is identified
var2 = int(input("Enter num2: ")) #variable two is identified
if(operation == "+"):
print (add(var1, var2))
elif(operation == "-"):
print (subtract(var1, var2))
elif(operation == "/"):
print (divide(var1, var2))
elif(operation == "*"):
print (multiply(var1, var2))
else:
print (power(var1, var2))
main()
input("Press enter to exit")
exit()
大約30分鐘前,我發現我的老Python的文件夾,並拍了一下從8我所有的基本腳本+個月前。我找到了我的計算器迷你腳本,並認爲在儘可能少的行中重新創建它會很有趣(我剛剛學習lambda)。這裏是我有什麼:
main = lambda operation,var1,var2: var1+var2 if operation=='+' else var1-var2 if operation=='-' else var1*var2 if operation=='*' else var1/var2 if operation=='/' else 'None'
print(main(input('What operation would you like to perform? [+,-,*,/]: '),int(input('Enter num1: ')),int(input('Enter num2: '))))
input('Press enter to exit')
我知道這是一個基於我的具體情況的個人問題,但我將不勝感激任何幫助使其縮短。有沒有辦法讓它變得更加Pythonic?我正確使用lambda?有沒有辦法處理我的縮短版本中的錯誤?任何幫助,將不勝感激。我對此很陌生。謝謝!
爲了使它更Python,把方法拿過來,讓人類可讀 – Sayse
此外,也許更適合[codereview.se],但發佈 – Sayse
@Adler之前檢查他們的準則:新增答案。這是你需要的嗎?將答案標記爲已接受,如果您在將來以其他方式查看時獲得了您想要的內容作爲參考 –