2013-12-15 29 views
1

我已經創建了這個計算器,但是現在我想通過創建一個錯誤消息「請只輸入數字」來改進它。但我在哪裏添加?創建我自己的錯誤信息?但是哪裏?

這是我的代碼:

def menu(): 
    print "Welcome to the calculator" 
    print "The options are 1) Addition 2)Subtraction 3)Multiplication 4)Division 5)Exit  Calculator" 
    return input("Choose your option") 

def add(a,b): 
    print a+b 

def sub(a,b): 
    print a-b 

def mult(a,b): 
    print a*b 

def div(a,b): 
    print a/b 

loop=1 
choice=0 
while loop==1: 
    choice=menu() 
    if choice==1: 
     add(input("Enter first number"),input("Enter second number")) 
    elif choice==2: 
     sub(input("Enter first number"),input("Enter second number")) 
    elif choice==3: 
      mult(input("Enter first number"),input("Enter second number")) 
    elif choice==4: 
      div(input("Enter first number"),input("Enter second number")) 

    elif choice==5: 
       loop=0 
       exit() 

感謝:-)

回答

0

對於每個choice情況下,你可能想存儲的輸入值,並對其進行驗證。

if choice == 1: 
    a = input("Enter first number:") 
    while (type(a) != int and type(a) != float): 
     a = input("Not a number. Enter first number:") 
    b = input("Enter second number:") 
    while (type(b) != int and type(b) != float): 
     b = input("Not a number. Enter first number:") 
    add(a, b) 
+0

這是有道理的,但是我不能讓它工作?我不知道爲什麼。 當我測試它時,它仍然會出現消息「q(或任何我輸入的字母」未定義「) 非常感謝 – user3105095

+0

@ user3105095您在進行類型檢查之前是否忘記了指定給'q'?答案的第二行:'a = input(「輸入第一個數字:」)' –

+0

您還應該考慮使用'isinstance(a,numbers.Number)'(在導入['numbers']之後(http:// docs.python.org/3.3/library/numbers.html))而不是'type(a)!= int和type(a)!= float'。使用'isinstance'意味着你的代碼可以處理任何類型的數字,包括複數:) –

1

的基本思想是利用raw_input而不是input。這給了我們一個來自用戶的字符串,我們測試它是否是一個數字。如果它不是一個數字,我們再問一次。

def myInput(message): 

    # loop forever/until we have a valid input 
    while True: 

     # ask user for input 
     user_input = raw_input(message) 

     # check if its a number 
     try: 
      result = float(user_input) 

      # Valid input, return the result 
      return result 

     except ValueError: 
      # It couldn't be converted to a number, ask again 
      print "Please only enter numbers" 

      # Repeat the loop/ask again 
      continue 
的地方

然後,你正在使用input('some message')使用myInput('some message')

0

@ Christian's已經回答了你的直接問題,所以我將爲你的功能提供一些簡單的改進。

您可以改進此代碼的一種簡單方法是爲您的循環控制變量使用明確的TrueFalse值。這有助於防止您稍後犯錯並將loop設置爲無效值。

您也可以在if塊之外提取「輸入第一個數字」,「輸入第二個數字」以減少重複。

您還應該嘗試更一致地使用縮進。

should_loop = True 
while should_loop: 
    choice = menu() 
    x = input("Enter first number") 
    y = input("Enter second number") 

    if choice == 1: 
     add(x,y) 
    elif choice == 2: 
     sub(x,y) 
    elif choice == 3: 
     mult(x,y) 
    elif choice == 4: 
     div(x,y) 
    elif choice == 5: 
     should_loop = False 
     exit()