2017-04-17 89 views
0

我正在製作一個多重計算器,而且我幾乎把它關閉了,問題是當我詢問一個數字時,如果用戶給出了一個字符串輸入,代碼就會中斷並拋出一個錯誤,即使對於if聲明,我有一個else:if/else語句中的代碼打破

def Start(): 
    numberOneList = [] 
    numberTwoList = [] 
    multiples = 100000 
    iterations = 0 
    multiplicity = int(input("How many common multiplicities you would like to find between two numbers: ")) 

    if multiplicity > 0 and multiplicity < 100001: 
     numberOne = int(input("Input the first number: ")) 
     if numberOne > 0 and numberOne < 100001: 
      numberTwo = int(input("Input the second number: ")) 
      if numberTwo > 0 and numberTwo < 100001: 
       for i in range(multiples): 
        mNumberOne = numberOne * i 
        numberOneList.append(mNumberOne) 
        mNumberTwo = numberTwo * i 
        numberTwoList.append(mNumberTwo) 
       print("") 
       print("Common multiplicities:") 
       print("") 
       print("Calculating...") 
       print("") 
       for i in numberOneList: 
        for a in numberTwoList: 
         if a == i: 
          if a != 0: 
           print(numberOne, "x", i/numberOne, "=", i) 
           print(numberTwo, "x", a/numberTwo, "=", a) 
           print("") 
           iterations += 1 
           if iterations == multiplicity: 
            Again() 
           else: 
            continue 
          else: 
           continue 
         else: 
          continue 
      else: 
       print("Invalid answer, restarting") 
       Start() 
     else: 
      print("Invalid answer, restarting") 
      Start() 
    else: 
     print("Invalid answer, restarting") 
     Start() 

def Again(): 
    calculateAgain = input("Calculate again? [y/n]: ") 
    if calculateAgain == "y": 
     Start() 
    if calculateAgain == "n": 
     quit() 
    else: 
     Again() 

Start() 
+1

這是因爲'else'語句無關捕捉錯誤。你需要使用'try/except'。 – kindall

+4

我強烈建議不要使用遞歸來再次運行你的函數......使用'while'循環。 –

回答

0

,因爲你是在斷言用戶的輸入的int類型,而不檢查,以確保這是有效的第一你得到一個錯誤。由於@ kindall在comment中提到,try/except允許您捕獲失敗的類型斷言並正常處理它們。結束語您int的東西,如注塑以下應該做的伎倆:

try: 
    multiplicity = int(input("How many common multiplicities you would like to find between two numbers: ")) 
except ValueError as e: 
    print('Please input a valid number') 
    return str(e) 

(注意,而不是返回錯誤文本,你可能只是重複的提示符)

+0

感謝您的幫助,它像一個魅力! –

+0

另請注意,您應該避免除了泛型異常。在這種情況下使用ValueError。 – DSLima90

0

一個快速解決當前的代碼是創建一個函數來獲取輸入或無效的值,如果它不是一個int

def input_positive_integer(message): 
    while(True): 
     try: 
      value = int(input(message)) 
      if (value<=0 or value > 100000): 
       raise ValueError("Not in range") 
      break 
     except ValueError as e: 
      print("Value error!! Try again!") 

然後你就可以改變你所有的輸入,接收整數使用此功能。

請注意,它將保持循環,直到該值有效。

我真的建議你避免在代碼遞歸,請嘗試使用一個簡單的while循環...