这是我的计算器。我做到了,因为我的朋友向我挑战,让它成为12行。和我DID!现在我试图缩短它,但理论上它不可能更短: 程序必须: 1:解释所有内容并要求输入(第一行) 2:接受输入(第二行) 3:打印(答案) 4至12:由逻辑和操作组成。缩短我的计算器代码(python3)
我请大家看看我的代码,并教我一些新的: 如何使它少于12行!
在此先感谢! (PS。我没有做这个学校,这仅仅是为了好玩,我学到了我自己的时间)
以下是在Python 3:
print("\n enter 'first number' \n then the 'second number' \n then enter the 'type of operation': + - */ ")
a,b,c = [(input("Enter : ")) for i in range(0,3) ]
def op(a,b,c):
if c == '+':
return(float(a)+float(b))
elif c == '*':
return(float(a)*float(b))
elif c == '/':
return(float(a)/float(b))
elif c == '-':
return(float(a)-float(b))
print('your answer is: ',op(a,b,c))
如果仅仅是行数:1和2可以合并,你的'if' /'elif'语句可以从两行减少到一行。但是我会使用'operator'模块中的运算符字典来代替:'ops = {'+':operator .__ add__,...}' –