2017-04-20 54 views
-2

这是我的计算器。我做到了,因为我的朋友向我挑战,让它成为12行。和我DID!现在我试图缩短它,但理论上它不可能更短: 程序必须: 1:解释所有内容并要求输入(第一行) 2:接受输入(第二行) 3:打印(答案) 4至1​​2:由逻辑和操作组成。缩短我的计算器代码(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)) 
+0

如果仅仅是行数:1和2可以合并,你的'if' /'elif'语句可以从两行减少到一行。但是我会使用'operator'模块中的运算符字典来代替:'ops = {'+':operator .__ add__,...}' –

回答

1

首先,你可以使用astliteral_eval安全地直接评估字符串文字。

import ast 
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): 
    return ast.literal_eval("%f%s%f"%(a, c, b)) 
print('your answer is: ',op(a,b,c)) 

或者,如果你想算线,cheaty,但凌乱,一个行的解决办法是:

print("\n enter 'first number' \n then the 'second number' \n then enter the 'type of operation': + - */ ");print('your answer is: ',__import__("ast").literal_eval("{0}{2}{1}".format(*[float(input("Enter : ")) if i != 2 else input("Enter : ") for i in range(0,3)]))) 
+0

方法定义不是必需的 –

+0

@abccd wOw。谢谢 – KOOLz