这是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?有没有办法处理我的简化版本中的错误?任何帮助,将不胜感激。我对此很陌生。谢谢!
最佳答案
为了简化代码,我建议:
注意:根据用户提到的要求,我使用
lambda
函数来替代方法。我个人将使用 operator
使用
operator
:import operator
def perform_operation(my_operator):
return {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv, # "operator.div" in python 2
'^': operator.pow,
}.get(my_operator, '^') # using `^` as defualt value since in your
# "else" block you are calculating the `pow`
使用
lambda
:def perform_operation(my_operator):
return {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / float(y),
'^': lambda x, y: x ** y,
}.get(my_operator, '^') # using `^` as defualt value since in your
# "else" block you are calculating the `pow()`
sample 运行:
>>> perform_operation('/')(3, 5)
0.6
PS:看一下定义,您会知道为什么使用
operator
比lambda
更加pythonic else
块以使其调用为:var1 = int(input("Enter num1: "))
var2 = int(input("Enter num2: "))
perform_operation(operation)(var1, var2) # Making call to function created above
# THE END - nothing more in else block
if
的条件:if operation not in ["+", "-", "*", "/", "^"]:
# invalid operation
关于python - 简化代码-根据运算符执行数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40255043/