2016-10-26 5 views
-2

に基づいて数学的な操作を実行するには、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からすべての私の基本的なスクリプトを見てみました+ヶ月前。私は電卓のミニスクリプトを見つけ、可能な限り数行で再作成するのが楽しいと思った(私はラムダを学んでいる)。ここで私が持っているものです。

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にする方法はありますか?ラムダを正しく使用していますか?短縮バージョンのエラーを処理する方法はありますか?どんな助けもありがとう。私はこれに非常に新しいです。ありがとう!

+1

、それはより多くのニシキヘビ作るにバックメソッドを入れて、それは人間が読める – Sayse

+0

[codereview.se]にも、おそらくより適していますが、 – Sayse

+0

@Adler投稿する前に、彼らのガイドラインを確認するには:追加答えを。これはあなたが必要とするものですか?将来的に他の人が見たいと思ったものを達成したら、受け入れられたものとしてマークしてください。 –

答えて

0

コードを簡単にするために、私がすることをお勧めします:辞書の助けを取って操作を実行するための関数を作成します

  1. 注:私は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()` 
    

    サンプル実行:

    >>> perform_operation('/')(3, 5) 
    0.6 
    

    PS:あなたが持っているでしょうdefinationを見ますなぜアイデア

    if operation not in ["+", "-", "*", "/", "^"]: 
        # invalid operation 
    

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条件と簡素化:使用してoperatorはように電話をかけるためにあなたのelseブロックを更新lambda

  • よりニシキヘビです

  • +0

    うわー、ありがとう!私は「演算子」を認識していなかったので、すべてを簡単に解釈できるようになりました。将来私は間違いなくそれを使用します。ラムダは混乱しており、しばしば読みにくい。私は答えを感謝します。 –

    0

    これは楽しい自己チャレンジ(と私はあなたがそれをどれくらいうまく圧縮しているかに感心している)だと理解していますが、ラムダとピジョンソニックについての一般的なアドバイスもあります。インラインコードを実行しているときにのみ使用してください。

    PEP-8は、ラムダを使用する唯一の利点は、大きな表現の中に埋め込むことができるということです。例えば:それはあなたのスタックトレースと理解する上で貴重な情報を与えるので

    result = sorted(some_weird_iterable, key=lambda x: abs(x[0] - x[-1])) 
    

    メソッドにIDを割り当てたい

    は、常に defを使用しています。実際、もしそれが最も重要な事柄を超えていれば、あなたがしていることを明確にするためにラムダを完全に避けることを勧めます。

    def as_the_bird_flies_distance(x): 
        return abs(x[0] - x[-1]) 
    
    result = sorted(some_weird_iterable, key=as_the_bird_flies_distance) 
    

    さらに「Pythonic」を作成するという概念は、短縮することではありません。しかし、読みやすく、維持し、拡張することを容易にする。

    Python 2.7.11 (default, Jan 22 2016, 08:29:18) 
    [GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin 
    Type "help", "copyright", "credits" or "license" for more information. 
    >>> import this 
    The Zen of Python, by Tim Peters 
    
    Beautiful is better than ugly. 
    Explicit is better than implicit. 
    Simple is better than complex. 
    Complex is better than complicated. 
    Flat is better than nested. 
    Sparse is better than dense. 
    Readability counts. 
    Special cases aren't special enough to break the rules. 
    Although practicality beats purity. 
    Errors should never pass silently. 
    Unless explicitly silenced. 
    In the face of ambiguity, refuse the temptation to guess. 
    There should be one-- and preferably only one --obvious way to do it. 
    Although that way may not be obvious at first unless you're Dutch. 
    Now is better than never. 
    Although never is often better than *right* now. 
    If the implementation is hard to explain, it's a bad idea. 
    If the implementation is easy to explain, it may be a good idea. 
    Namespaces are one honking great idea -- let's do more of those! 
    
    +0

    チップをありがとう。私が最初に 'lambda'を発見したとき、私はそれを式の中のpygameファイルで見つけました。なぜ誰かが必要以上に複雑なものを作ってしまうのは混乱していましたが、今は見ています。ラムダは便利です。ジャンプするのを避けることができます(あなたの言ったように、1行に埋め込むこともできます)。しかし、作成している関数が単純ではない場合は混乱します。それはラムダの考えですか?応答していただきありがとうございます。私は最終的になぜより長く、より間隔の広いコードが好まれるのかを理解しています。 –

    +0

    @AdlerWeberは間違いありません。もしラムダが明確にするのに役立たないなら、それを使用しないでください。デバッグするのが難しくなり、後で戻ってみるとあなたを混乱させるだけです。 – SCB

    関連する問題