【发布时间】:2017-03-08 09:25:27
【问题描述】:
以下是 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?有没有办法处理我的缩短版本中的错误?任何帮助,将不胜感激。我对此很陌生。谢谢!
【问题讨论】:
-
为了让它更pythonic,把方法放回去,让它可读
-
另外,可能更适合Code Review,但发帖前请查看他们的指南
-
@Adler:添加了答案。这是你需要的吗?如果您实现了您想要的其他人在将来查看它作为参考,请将答案标记为已接受
标签: python python-3.x lambda error-handling operators