2013-11-28 76 views
0

我落後在以下幾個基本的腳本不應該問進入A和B的輸入邏輯類甚至給不相關的數字,是大於5簡單的計算器使用Python

#!/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" 
+0

如果您也許改變 「<=" to "> =」? –

回答

1

您可以將它檢查用戶輸入至t錯誤條件他行旁邊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

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() 
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()