2017-04-03 117 views
0

我正在嘗試讓用戶輸入8位數的條形碼。如果代碼不是8位數字,則會打印一條錯誤消息。如果它是8位數字,則會引發錯誤。爲什麼此代碼會產生縮進/語法錯誤

def get_user_input(): 
    global total_price 
    """ get input from user """ 
while len(str(GTIN))!=8: 
    try: 
     GTIN = int(input("input your gtin-8 number:")) 
     if len(str(GTIN))!=8: 
      print("make sure the length of the barcode is 8") 
     else: 
      print("make sure you enter a valid number") 
     return GTIN 
+1

的就是你得到的語法錯誤。請分享錯誤/堆棧跟蹤。 –

+0

在此功能之後,我在下一行獲得未壓縮的縮進 – Yeas123

+2

請確保您粘貼的縮進是正確的,因爲現在您的'while'處於主執行級別,* not * in'get_user_input'功能。 – Ajean

回答

0

實際上有幾個錯誤會在這裏:

  1. 你壓痕正在處理的while循環是在函數外。 Python中的Witespace很重要。
  2. 它需要有一個除了每個try語句。
  3. 此外,GTIN從未最初定義,我修正了這一點。

您的新代碼:

def get_user_input(): 
    global total_price 
    """ get input from user """ 
    GTIN = "" 
    while True: 
     try: 
      GTIN = int(input("input your gtin-8 number:")) 
      if len(str(GTIN)) == 8: 
       break 
      else: 
       print("make sure the length of the barcode is 8") 
     except: 
      pass 
    return GTIN 
get_user_input() 
+0

UnboundLocalError:分配之前引用的局部變量'GTIN' – Yeas123

+0

剛更新它。如果你能標記爲解決方案,這將有很大幫助。 – Neil

+0

謝謝,它的工作原理,但是如何我會讓它繼續下去,如果我輸入一個小於8的輸入錯誤出現,但是如果我再次輸入它的代碼只是繼續 – Yeas123

相關問題