在python类的简单计算器

时间:2013-11-28 18:25:02

标签: python python-2.7 logic calculator

我在逻辑上滞后,即使在给出大于5的无关数字之后,以下基本脚本也不应该要求输入A和B的输入。

#!/usr/bin/python
try :
     print "Enter 1 for Addition "
     print "Enter 2 for Subtraction"
     print "Enter 3 for Multiplication"
     print "Enter 4 for Divition"

     class calc :

        def Add ( self, A, B ):
           print A + B
        def Sub (self, A, B ):
           print A - B
        def Mul (self, A, B ):
           print A * B
        def Div (self, A, B ):
           print A / B

    C = calc()

    Input = int (raw_input ("Enter the choice:"))

    A = int (raw_input ("Enter A:"))
    B = int (raw_input ("Enter B:"))

    if Input == 1:
          C.Add (A,B)
    elif Input == 2:
          C.Sub (A,B)
    elif Input == 3:
          C.Mul (A,B)
    elif Input == 4:
          C.Div (A,B)
    elif Input <= 5:
          print "Its not avaliable try again"
          exit ()

except ValueError:
      "The value is wrong"

3 个答案:

答案 0 :(得分:2)

使用if ... elif结构可以更好地处理整个dict链:

try:
    {1: C.Add, 2: C.Sub, 3: C.Mul, 4: C.Div}.get(Input)(A,B)
except TypeError: 
    print "It's not available, try again"
    exit()

答案 1 :(得分:1)

您可以将检查错误用户输入的条件移动到raw_input调用旁边的行(并在语句本身中修复问题 - 错误的选择是大于4且小于0的选项):

C = calc()

Input = int (raw_input ("Enter the choice:"))

if Input not in [1,2,3,4]:
    print "Its not avaliable try again"
    exit ()

BTW:最好只在try/except块中包含可能导致异常的行,而不是整个程序:

C = calc()
try:
    Input = int (raw_input ("Enter the choice:"))
except ValueError:
    print "Wrong input"
    exit()

if Input not in [1,2,3,4]:
    print "Its not avaliable try again"
    exit ()

此外,最好使用命名约定:变量名称应以非大写字母开头,例如input,类的名称应以大写字母开头 - class Calc

答案 2 :(得分:0)

而不是

... 
elif Input <= 5: # This doesn't make sense, this check will work just for negative numbers
    print "Its not avaliable try again"
    exit ()

使用

...
else:
    print "Its not avaliable try again"
    exit ()